首页 > 解决方案 > Firestore数据的角度循环

问题描述

我有一个 Angular 应用程序,它使用 Firebase 来托管和 Firestore 来存储我的数据。我想创建一个函数,它读取特定集合的所有数据并循环遍历文档以执行特定操作(上传到已经编码的 Google Drive)。

但是,我正在努力遍历我的 Firestore 集合中的文档。这是我从 Firestore 中的“测试”集合中读取数据的代码:

read() {
    let result = [];

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

    return result;
  }

在另一个组件中,当我调用这个 read() 函数并 console.log 它时,我可以看到集合中的所有数据。但是,当我尝试循环遍历文档并分别对它们进行 console.log 时,它不会输出任何内容。

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
}

我错过了一些明显的东西吗?

标签: angularfirebasegoogle-cloud-firestore

解决方案


经过一番挖掘,我发现我的代码存在问题。问题在于将读取操作的结果分配给变量allRows

而不是这个:

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

这对我有用:

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

推荐阅读