Angular Firestore - Get document data and assign to variable inside the component

Viewed 126

I'm using Angular Firestore to get and filter the data base on the timestamp.

The only issue is whenever I get the doc.data(), I can't assign it to a variable so that I can use this variable anywhere inside the component.

Component.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)
            })
          }); 
    
  }

I assigned the wilsData like this:

  private wilsData: any[];

I get undefined value when I log it.

So the question is, how can I assign the doc.data() to a variable?

Thanks for your help

1 Answers

You need to initialize the array:

 private wilsData: any[] = [];
Related