Ad

How To Get Object From Database Using It's Key?

I want to get an Object from database using it's key, but it is not working.

Here is my database :

DATABASE

DATABASE:

...
 - toc-list
           |___ id1 (generated by firebase)
                  |___ field1
                  |___ field2

           |___ id2 (generated by firebase)
                  |___ field1
                  |___ field2

           |___ id3 (generated by firebase)
                  |___ field1
                  |___ field2

I am trying to get an Object from toc-list by using the id1 "-Ld6AAdHn6JBYcrh29Xz"

I have tried to get it like this, but it is not working :

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';

import firebase from 'firebase';
import { AngularFireDatabase, AngularFireList } from 'angularfire2/database';

@IonicPage()
@Component({
  selector: 'page-confrontation-1',
  templateUrl: 'confrontation-1.html',
})
export class Confrontation_1Page {

  toc_id : string;
  public toc: Array<any> = [];
  public tocRef: firebase.database.Reference = firebase.database().ref('/toc-list');

  constructor(public navCtrl: NavController, public navParams: NavParams, public afDB: AngularFireDatabase) {
    this.toc_id = navParams.get('tocId');
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad Confrontation_1Page');

    // I want to show the details of the element that has the id : toc_id
    console.log(this.afDB.object('/toc-list/' + this.toc_id));

  }


}

Ad

Answer

Observable are async and you have to subscribe on it. Try:

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';

import firebase from 'firebase';
import { AngularFireDatabase, AngularFireList } from 'angularfire2/database';

@IonicPage()
@Component({
  selector: 'page-confrontation-1',
  templateUrl: 'confrontation-1.html',
})
export class Confrontation_1Page {

  toc_id : string;
  public toc: Array<any> = [];
  public tocRef: firebase.database.Reference = firebase.database().ref('/toc-list');

  constructor(public navCtrl: NavController, public navParams: NavParams, public afDB: AngularFireDatabase) {
    this.toc_id = navParams.get('tocId');
    this.afDB.object('/toc-list/' + this.toc_id).valueChanges().subscribe(res => console.log(res))
  }

  ionViewDidLeave() {
    this.afDB.object('/toc-list/' + this.toc_id).valueChanges().unsubscribe();
  }


}
Ad
source: stackoverflow.com
Ad