javascript - 将 FirestoreCollection 转换为数组?
问题描述
我很难将 Firestore 数据转换为 chart.js 图的数组。
从 Firestore 获取数据
fetchData(){
//Get data
this.updatesCollection = this.afs.collection(pathStats);
this.updates = this.updatesCollection.valueChanges();
}
创建图表
createChart(){
this.chart = new Chart('canvas', {
type: 'line',
data: {
labels: ['5/18/18', '5/19/18', '5/20/18', '5/21/18', '5/22/18', '5/23/18'],
datasets: [{
label: 'Filled',
backgroundColor: 'gray',
data: [4, 3, 5, 2, 6, 7],
fill: true,
}]
},
}
)
我现在使用硬编码值[4, 3, 5, 2, 6, 7]
作为我的数据点的占位符。我将如何使用来自 Firestore 的值?
解决方案
正如Ohad在下面提到的:
let chartData;
this.updatesCollection.ref.get().then((querySnapshot) => {
chartData = querySnapshot.docs.map(doc => doc.data());
}
这将为您提供一个数组,其中每个文档都在其自己的索引中。您可以像访问任何其他对象(即chartData[0].wheelCount
)一样访问单个属性。
解决方案
调用this.updatesCollection.get()
将异步返回一个querySnapshot
对象。
AquerySnapshot
有一个属性,它是一个包含零个或多个对象docs
的数组。documentSnapshot
这些中的数据可以用该.data()
方法提取。
生成数组的代码可能如下所示:
let chartData = this.updates.collection.get()
.then(querySnapshot => {
chartData = querySnapshot.docs.map(doc => doc.data())
})
推荐阅读
- c++ - 基于范围的 for 循环,第一项的特殊情况
- python - 将分类属性转换为python pandas中的多个属性
- typescript - 剩余参数必须是数组类型
- regex - 将 re.sub 命令行转换为 Apps 脚本
- amazon-web-services - 无法将列表值传递给 apigateway 更新方法,参数 patchOperations[2].value 的类型无效
- javascript - 显示 4 个不同国家的当前时间
- java - 当帖子在 UI 上真正发生时,在控制台上不断收到 400 个错误请求以进行帖子请求
- c++ - Golang 的 SWIG Coolprop 包装
- javascript - 不能从父构造函数继承属性
- file-upload - Upload .ipynb to wix blog