nOnInit
页面上的我使用async函数从firebase加载一些数据(通常async函数会等待从firebase中获取所有数据),因此此方法可以正常工作,并且我将数据保存在对象中getDocu
async ngOnInit() {
this.getDocu = await this.Help.getLastTime('JOURNALIER', 'Le Mat', 'lastTime', 'lastTime');
this.loadItems();
}
然后,在此页面内,用户填写一些问题,我将结果保存在Firebase的同一文档(更新)中,当我回到页面时,我运行ionViewWillEnter
重新加载更新的数据并显示在我的页面上。
async ionViewWillEnter() {
this.getDocu = await this.Help.getLastTime('JOURNALIER', 'Le Mat', 'lastTime', 'lastTime');
this.loadItems();
}
这是我的getLastTime
函数:
async getLastTime(collectionName: string, user: string, collec: string, docu: string) {
const docRef = this.afs.firestore.collection(collectionName).doc(user).collection(collec).doc(docu);
const doc = await docRef.get();
if (doc.exists) {
this.getDocu = doc.data();
} else {
this.getDocu = 'Never done';
}
return this.getDocu;
}
但是,当我控制台记录ionViewWillEnter
的结果时,我不会加载更新的数据,或者如果我手动重新加载页面,则这次ngOnInit
会运行并获得更新的值。 ..
对我来说很奇怪,因为看起来我使用相同的方法来获取值...结果不同。
答案 0 :(得分:3)
使用.valueChanges()
或.snapShotChanges()
代替.get()
。您可以订阅以前的方法,这使调用ionViewWillEnter()
之类的查询成为过时的方法。值更新后,您将自动再次接收值。
重写getLastTime()
(假设它在服务firebaseService
中)以返回一个Observable:
getLastTime(collectionName: string, user: string, collec: string, docu: string) {
return this.afs.collection(collectionName).doc(user).collection(collec).doc(docu).valueChanges();
}
在您的组件中,订阅getLastTime()
:
this.firebaseService.getLastTime(....).subscribe(res => {
if (!res)
console.log("never done");
});