首页 > 解决方案 > Firestore 获取数据的时间太长,因此我无法显示它

问题描述

我有一个从 Firestore 获取数据的函数:

  getLastTime(collectionName: string) {
    const docRef = this.afs.firestore.collection(collectionName).doc(this.User).collection('lastTime').doc('lastTime');
    docRef.get().then(doc => {
      if (doc.exists) {
          this.get = doc.data().lastTime;
      } else {
          this.get = 'Never done';
      }
  }).catch(error => {
      console.log('Error getting document:', error);
  });
    return this.get;
  }

对于我的测试,我实际上在文档“lastTime”中有一个字符串值,它是一个字符串。

在 ngOnInit() 中,我调用了我的函数并 console.log 了结果

this.InjuredLastTime = this.getLastTime('INJURY');
console.log(this. this.InjuredLastTime);

通常我应该在控制台内打印我的字符串,但我没有定义......

也许是因为 Firestore 没有足够快地获取我的数据,但我很惊讶,因为 Firestore 正常速度很快......

标签: javascriptfirebasegoogle-cloud-firestore

解决方案


docRef.get()getLastTime(). 因此,除非对 firebase 的调用是即时的(例如从不),否则这是行不通的。

正确的解决方案真的取决于你在做什么this.InjuredLastTime。但一种方法是返回一个承诺并在它准备好后设置它:

getLastTime(collectionName: string) {
    const docRef = this.afs.firestore.collection(collectionName).doc(this.User).collection('lastTime').doc('lastTime');
    return docRef.get().then(doc => {
      if (doc.exists) {
          return doc.data().lastTime;
      } else {
          return 'Never done';
      }
    }).catch(error => {
      console.log('Error getting document:', error);
      return null;
    });
}

然后,不是同步分配,而是异步执行:

this.getLastTime('INJURY').then(result => { this.InjuredLastTime = result });

推荐阅读