为什么服务构造函数不使用路由器在页面加载时传输angularfire2集合数据?

时间:2017-11-28 17:04:42

标签: angular firebase angularfire2 google-cloud-firestore

我正在网页上工作,我正在尝试在其中一个组件上显示来自firebase firestore的数据。该组件应该显示页面上的所有相关数据,并从搜索栏进行搜索。

我正在使用名为:searchComponent和cardComponent。

的组件
  • cardComponent 显示每个数据点。
  • searchComponent 使用 cardsService 从firestore获取数据,并通过使用@input从数据库传递卡片来显示所有cardComponents。

一切都很实用。但是代码并没有像我想象的那样有效。当我尝试从构造函数中的firestore传输集合数据时,页面只会在使用url导航或刷新页面时才加载该数据。如果我通过单击路由器链接导航页面,则数据不可见。

一旦我改为在ngOnInit函数中获取snapshotChanges或valueChanges,一切都开始工作了。

这是没有在路由器负载上显示数据的构造函数代码。

constructor(public afs: AngularFirestore) {
this.cardsCollection = this.afs.collection('cards', ref => ref.orderBy('author', 'asc'));
this.cards = this.cardsCollection.snapshotChanges().map(changes => {
  return changes.map(a => {
    const data = a.payload.doc.data() as Card;
    data.id = a.payload.doc.id;
    return data;
  });
});

}

目前我将其更改为在构造函数中获取cardsCollection并在ngOnInit中进行更改。

constructor(public afs: AngularFirestore) {
  this.cardsCollection = this.afs.collection('cards', ref => ref.orderBy('author', 'asc'));
}

ngOnInit() {
  this.cards = this.cardsCollection.snapshotChanges().map(changes => {
    return changes.map(a => {
      const data = a.payload.doc.data() as Card;
      data.id = a.payload.doc.id;
      return data;
    });
  });
}

此代码正常运行。但我的问题是为什么?第一个代码有什么问题?

0 个答案:

没有答案