将 FirestoreCollection 转换为数组?

2024-03-23

我在将 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 的值?

Solution

正如奥哈德在下面提到的:

let chartData;

this.updatesCollection.ref.get().then((querySnapshot) => {
    chartData = querySnapshot.docs.map(doc => doc.data());
}

这将为您提供一个数组,其中每个文档都有自己的索引。您可以像访问任何其他对象一样访问各个属性(即chartData[0].wheelCount).


Calling this.updatesCollection.get()将异步返回一个querySnapshot目的。

A querySnapshot has a docs属性是包含零个或多个的数组documentSnapshot对象。可以使用以下命令提取其中的数据.data() method.

生成数组的代码可能如下所示:

let chartData = this.updates.collection.get()
  .then(querySnapshot => {
    chartData = querySnapshot.docs.map(doc => doc.data())
  })
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将 FirestoreCollection 转换为数组? 的相关文章

随机推荐