angular - 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
}
我错过了一些明显的东西吗?
解决方案
经过一番挖掘,我发现我的代码存在问题。问题在于将读取操作的结果分配给变量allRows
。
而不是这个:
let allRows = await this.firebase.read();
这对我有用:
let allRows: any;
await this.firebase.read().then(result => allRows = result);
推荐阅读
- android - 将图像上传到 Firebase 时出现 StorageReference 错误
- javascript - javascript表达式不返回true,当我认为它应该......?
- bash - 如何在 vbscript 中运行 .sh 文件,或者如何在 vbscript 中执行 shell 脚本?
- python - Python jaeger-client 跟踪器未报告重用
- python - 使用三个 1D Numpy 数组的值创建 3D 数组
- mysql - MariaDB 升级(从 10.1 到 10.4.6)后,触发器停止按预期运行
- python - 如何在文本文件中保存和打开嵌套列表和字典?
- javascript - 反应处理多输入值
- java - 存储列表