首页 > 解决方案 > 如何更新 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;

标签: javascriptarraysangularcharts

解决方案


 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 = [];
      }

推荐阅读