首页 > 解决方案 > Angular Firestore - 获取文档数据并分配给组件内的变量

问题描述

我正在使用 Angular Firestore 根据时间戳获取和过滤数据库。

唯一的问题是每当我获得 doc.data() 时,我无法将其分配给变量,以便我可以在组件内的任何位置使用此变量。

组件.ts

joinData(toData, fromData){
    let toDate = toData
    let fromDate = fromData
    console.log("valueToDate : ", toDate)
    let dateTo = new Date(toDate).getTime() / 1000;
    let dateFrom = new Date(fromDate).getTime() / 1000;
    console.log("dateTo :", dateTo)


          let collection = this.fstore.firestore.collection('data_reports').where('timestamp', '>=', dateFrom).where('timestamp', '<=', dateTo);
          collection.get().then(function(querySnapshot) {
            querySnapshot.forEach(function(doc) {
              console.log("data: ", doc.data()) // ---> this line I can get the doc.data()
              this.wilsData = doc.data();       // ---> this line the value of wilsData is undefined
              console.log("wilsData: ", this.wilsData)
            })
          }); 
    
  }

我像这样分配了 wilsData:

  private wilsData: any[];

undefined当我记录它时,我得到了价值。

所以问题是,如何将 doc.data() 分配给变量?

谢谢你的帮助

标签: angularfirebasegoogle-cloud-firestoreangularfire

解决方案


您需要初始化数组:

 private wilsData: any[] = [];

推荐阅读