vdvaxel
vdvaxel

Reputation: 137

Angular loop over Firestore data

I have an Angular app using Firebase for hosting and Firestore for storing my data. I would like to create a function which reads all the data for a specific collection and loop over the documents to perform a certain action (upload to Google Drive, which has already been coded).

However, I am struggling to loop over the documents in my Firestore collection. This is my code to read the data from my "test" collection in Firestore:

read() {
    let result = [];

    this.firestore
      .collection("test")
      .snapshotChanges()
      .subscribe(item => {
        item.map(row => {
          result.push(row.payload.doc.data());
        })
      })

    return result;
  }

In another component when I call this read() function and console.log it, I can see all data in the collection. However, when I try to loop over the documents and console.log them individually, it doesn't output anything.

async doSomething() {
    let allRows = await this.firebase.read();  // the function shown above
    console.log(allRows);  // I can see all the "rows"/documents in the collection

    allRows.forEach(item => console.log(item)); // but if I do this, it doesn't output anything
    console.log(allRows.length);  // even this outputs 0
}

Am I missing something obvious?

Upvotes: 0

Views: 728

Answers (2)

vdvaxel
vdvaxel

Reputation: 137

After some digging I found the issue with my code. The issue is with assigning the result of the read operation to the variable allRows.

Instead of this:

let allRows = await this.firebase.read();

This worked for me:

let allRows: any;
await this.firebase.read().then(result => allRows = result);

Upvotes: 1

Sayooj V R
Sayooj V R

Reputation: 2363

Your read method will not wait for the data from firestore since it is an asynchronous action and return blank array. You should change the read method like this

read() {
    return new Promise((resolve, reject) => {
      let result = [];
      this.firestore
        .collection("test")
        .snapshotChanges()
        .subscribe(item => {
          Array.from(item).forEach(row => {
            result.push(row.payload.doc.data());
          });
          resolve(result);
        });
    });
  }

Upvotes: 0

Related Questions