我有一个表单,可以将数据添加到 Firestore 并从 Firestore 渲染到 Chart.js (行)上。但是它不会自动更新图表。我该如何使用 firestore 集合中的新数据刷新图表? 我尝试使用
this.chart.update();
但不起作用。
此代码生成图表
createChart() {
this.aaService.getData(this.id).subscribe(
(aaServ) => {
this.data = aaServ;
})
const abc = this.data.map((item) => item.abc);
const xyz = this.data.map((item) => item.xyz);
this.chart = new Chart('MyChart', {
type: 'line',
data: {
labels: abc,
datasets: [
{
label: 'xyz',
data: xyzLabels,
backgroundColor: 'red',
},
],
},
options: {
aspectRatio: 2.5,
},
});
}
在服务中从firestore获取数据
getData(id:string){
return this.db
.collection('aaCollection')
.snapshotChanges()
.pipe(map(docArray => {
return docArray.map(doc => {
return {
abc: doc.payload.doc.data()['abc'],
xyz: doc.payload.doc.data()['xyz']
}
})
}
))
}
}
在组件中,当提交表单时存储在Firestore中并假设显示在图表上。
onSubmit(){
this.id = this.activatedRoute.snapshot.params["id"];
let aa: aaModel = {
ID: this.id,
xyz: this.testForm.value.xyz,
abc: this.testForm.value.abc,
}
this.aaService.addBodyMetrics(this.Id, aa);
}
假设
this.aaService.addBodyMetrics
返回一个 Observable,您应该订阅该 Observable,并在 observable 成功返回时调用 getChart
方法。
onSubmit(){
this.id = this.activatedRoute.snapshot.params["id"];
let aa: aaModel = {
ID: this.id,
xyz: this.testForm.value.xyz,
abc: this.testForm.value.abc,
}
this.aaService.addBodyMetrics(this.Id, aa)
.subscribe({
next: () => {
this.createChart();
}
});
}
在
createChart
方法中,Observable是异步的,您应该获取Observable返回的值并初始化图表数据和配置。因此,您应该将线从 const abc
一直移动到 subscribe
方法中。
createChart() {
this.aaService.getData(this.id).subscribe(
(aaServ) => {
this.data = aaServ;
const abc = this.data.map((item) => item.abc);
const xyz = this.data.map((item) => item.xyz);
this.chart = new Chart('MyChart', {
type: 'line',
data: {
labels: abc,
datasets: [
{
label: 'xyz',
data: xyzLabels,
backgroundColor: 'red',
},
],
},
options: {
aspectRatio: 2.5,
},
});
});
}