【问题标题】:AngularFire2: Getting empty object from databaseAngularFire2:从数据库中获取空对象
【发布时间】:2018-03-23 08:28:40
【问题描述】:

我正在关注 AngularFire2 为我的项目设置 Firebase 的文档。我无法从数据库中检索任何数据。

  contacts:Observable<any[]>;
  constructor(angularFire: AngularFirestore, public http: Http) { 
    this.contacts = angularFire.collection('mycontacts').valueChanges()   
    console.log("Contacts : "+ this.contacts)
  }

我的 Firebase JSON 结构如下:

"mycontacts" : {
"Contacts" : {
  "John" : {
    "Address" : "3 London Road",
    "Email" : "john@hotmail.com",
    "FirstName" : "John",
    "LastName" : "Snow",
    "PhoneNo" : "074236482878"
  }}}

结果:

【问题讨论】:

    标签: angular firebase firebase-realtime-database angular2-services angularfire2


    【解决方案1】:

    正如您正确定义的那样,组件中的contacts 属性是Observable。因此,只需 console.logging 它不会为您提供您正在寻找的数据。如果你想提取组件内部的数据,那么你必须使用subscribe订阅它

    angularFire.collection('mycontacts').valueChanges().subscribe((data) => {
     this.contacts = data;
    });
    

    话虽如此,如果您只想在页面(模板)上显示数据,那么您可以简单地使用 async 管道在页面上异步显示 Observable 数据。

    this.contacts = angularFire.collection('mycontacts').valueChanges(); // same code you had
    

    在您的模板中,例如使用管道

    <div *ngFor="let contact of contacts | async" [innerHTML]="contact"></div>
    

    希望对你有帮助。

    【讨论】:

    • 感谢 Amal,我收到以下错误“该项目未启用 Cloud Firestore API”
    猜你喜欢
    • 2016-12-10
    • 2016-11-10
    • 2018-07-27
    • 2018-07-19
    • 2018-10-03
    • 1970-01-01
    • 2020-03-08
    • 2014-09-17
    相关资源
    最近更新 更多