带有 Firestore 的异步函数不会加载我的数据

Async function with Firestore does not load my data

在我的 nOnInit 页面上,我使用异步函数从 firebase 加载一些数据(通常异步函数等待从 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 那 运行 s 并获得更新值...

对我来说很奇怪,因为看起来我使用相同的方法来获取值...但结果不同..

使用 .valueChanges().snapShotChanges() 而不是 .get()。您可以订阅以前的方法,这使得调用 ionViewWillEnter() 之类的查询已过时。更新值后,您将自动再次收到这些值。

重写getLastTime()(假设它在服务firebaseService中)为return一个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");
});