javascript - 如何更新 Chart js 中的标签?
问题描述
我在 Angular 中使用 Chart.js。当我在 Web 应用程序日历中选择日期时,休息服务会发送响应,更新图表,x 和 y 轴。在我的 x 轴上,我将日期作为字符串。但是,如果我的响应数据比以前少,(不是每个月都有相同的天数,或者不是每个响应都有相同数量的数据),x 轴不会缩小。
这个:
this.barChartLabels = this.xLabels; //an array with many elements
if (selectedDateFormated === "2021-9-28") {
this.barChartLabels = ["a","b","c","d"]; // overwrite for demo purpose
}
会给出这样的东西:
它应该只是 x 轴上的 a,b,c,d。怎么做?
我在我的 subscribe() 方法中有这个来删除以前的数据,然后再从 rest api 更新它们:
this.barChartLabels = [];
this.barChartData[0].data = [];
this.barChartData[1].data = [];
this.xLabels = [];
this.Consumption = [];
this.Flow = [];
this.chart.update();
this.resultSet.result.forEach(item => {
this.xLabels.push(
item.a
);
this.Flow.push(
+item.b //+ is casting string to number
);
this.Consumption.push(
+item.f
);
});
this.barChartLabels = this.xLabels;
this.barChartData[0].data = this.Consumption;
this.barChartData[1].data = this.Flow;
解决方案
this.chart.chart.config.data.labels = this.xLabels;
这上面的伎俩。图表是对视图中图表的引用:
@ViewChild(BaseChartDirective, { static: true }) chart: BaseChartDirective;
不知道this.chart.chart.config
它实际上做了什么以及为什么。这是关于 ng2-charts 中的一个错误。所以我做了这两个方法并在 subscribe() 方法的末尾调用它们,当来自 api 的响应被推送到我的数组中时。
refresh_chart() {
setTimeout(() => {
console.log("xLabels: " + this.xLabels);
console.log("Consumption: " + this.consumption);
if (this.chart && this.chart.chart && this.chart.chart.config) {
this.chart.chart.config.data.labels = this.xLabels;
this.chart.chart.config.data.datasets[0].data = this.consumption;
this.chart.chart.update();
}
});
}
clearCharts() {
this.barChartLabels= [];
this.emptyChartData(this.barChartData);
}
emptyChartData(obj) {
obj[0].data = [];
obj[1].data = [];
}
推荐阅读
- node.js - 我正在使用 React-native 和 node js。在得到 Node js 的响应后,我无法从一个屏幕导航到另一个屏幕
- android - 谷歌地图上的优步风格信息窗口
- python - 在 python 中(plt.table 在第一行设置 rowColours)
- python - 如何将 python 实例共享给 C++?
- spring - Spring:如何在 Spring MVC 中使用会话
- docker - Docker compose 在脚本下载文件之前
- xml - 元素“workOrder”:没有可用于验证根的匹配全局声明
- ssl - 将 .cer 转换为 .pem 返回错误“无法加载证书”
- python-2.7 - 在 python 中使用 urllib 库清除缓存
- python - python结构:设置环境变量