【问题标题】:How to retrieve data from firebase database with an observable如何使用 observable 从 firebase 数据库中检索数据
【发布时间】:2018-03-25 11:26:58
【问题描述】:

设置:

 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

【问题讨论】:

  • console.log('check', this.items);是否显示某些东西???
  • 编辑了我的帖子。
  • ` console.log('check', this.items);` 不适用于可观察对象。您需要订阅才能获取数据
  • this.items.subscribe(res=&gt;console.log(res))
  • @Hareesh 它返回给我这个:TypeError: this.items.subscribe is not a function

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


【解决方案1】:

Angularfire2 文档是这样说的

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

【讨论】:

    【解决方案2】:

    您可以将 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>
    

    【讨论】:

      【解决方案3】:

      从 RxJS 6 开始,您可以使用 from() 运算符,例如:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-11-27
        • 1970-01-01
        • 2020-07-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多