如何使用observable从firebase数据库中检索数据

时间:2018-03-25 11:26:59

标签: angular typescript firebase firebase-realtime-database angularfire2

设置:

 1. ionic: 3.20.0
 2. AngularFire2 V5.0.0-rc6
 3. Cordove: 8.0.0
 4. firebase: "^4.12.0"

我尝试从我的数据库中检索数据,如下所示:

import { AngularFireDatabase, FirebaseListObservable} from 'angularfire2/database';

FirebaseListObservable没有导出的成员' FirebaseListObservable'

export class HomePage {
   items: FirebaseListObservable<any[]>;

   constructor(
      public db: AngularFireDatabase
    ){

       this.items = db.list('/restaurant_menu');
       console.log('check', this.items);
    }
}

在html模板中:

<ion-list>
    <ion-item class="text" *ngFor="let item of items">
        {{item}}
    </ion-item>
</ion-list>

但这会让我回复:Error: Cannot find a differ supporting object '[object Object]'

console.log告诉我这个:

{query: Reference, update: ƒ, set: ƒ, push: ƒ, remove: ƒ, …}
auditTrail:ƒ (events)
push:ƒ (data)
query:Reference {repo: Repo, path: Path, queryParams_: QueryParams, orderByCalled_: false}
remove:ƒ remove(item)
set:ƒ dataOperation(item, value)
snapshotChanges:ƒ (events)
stateChanges:ƒ (events)
update:ƒ dataOperation(item, value)
valueChanges:ƒ (events)
__proto__: Object

3 个答案:

答案 0 :(得分:1)

以下是Angularfire2 doc所说的

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

export class HomePage {
   itemsRef: AngularFireList<any>;
   items: Observable<any[]>;

   constructor(
      public db: AngularFireDatabase
    ){

       this.itemsRef = db.list('restaurant_menu');
       this.items = this.itemsRef.valueChanges();
       this.items.subscribe(res=> console.log(res));
    }
}

您可以查看doc

答案 1 :(得分:0)

您可以将observable(valuechanges)存储在变量中,然后使用async标记。

   items$: Observable<any[]>;
  constructor(public db: AngularFireDatabase){
       this.items$ = this.db.list('/restaurant_menu').valueChanges();
    }

在你的HTML中

<ion-list>
    <ion-item class="text" *ngFor="let item of (items$ |async)">
        {{item}}
    </ion-item>
</ion-list>

答案 2 :(得分:0)

从RxJS 6开始,您可以像这样使用from()运算符:

getUsers(): Observable<firestore.DocumentSnapshot<firestore.DocumentData>> {
    return from(this.db.collection('users').get());
}