Firestore的异步功能不会加载我的数据

时间:2019-11-27 10:12:20

标签: angular typescript firebase google-cloud-firestore ionic4

我在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会运行并获得更新的值。 ..

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

1 个答案:

答案 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");
});