如何使用密钥从数据库中获取对象?

时间:2019-04-24 09:53:18

标签: angular typescript firebase ionic-framework firebase-realtime-database

我想使用它的密钥从数据库中获取一个对象,但是它不起作用。

这是我的数据库:

DATABASE

数据库:

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

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

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

我正在尝试使用id1“ -Ld6AAdHn6JBYcrh29Xz”从toc列表中获取对象

我试图这样得到它,但是它不起作用:

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));

  }


}

1 个答案:

答案 0 :(得分:1)

可观察到的是异步的,您必须对其进行订阅。试试:

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();
  }


}