我正在网页上工作,我正在尝试在其中一个组件上显示来自firebase firestore的数据。该组件应该显示页面上的所有相关数据,并从搜索栏进行搜索。
我正在使用名为:searchComponent和cardComponent。
的组件一切都很实用。但是代码并没有像我想象的那样有效。当我尝试从构造函数中的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;
});
});
}
此代码正常运行。但我的问题是为什么?第一个代码有什么问题?