【问题标题】:Chart isn't updating with Response data (Chart.js 3.2.1, ng2-charts 3.0.0-beta.9)图表未使用响应数据更新(Chart.js 3.2.1,ng2-charts 3.0.0-beta.9)
【发布时间】:2021-07-30 22:15:22
【问题描述】:

我正在使用 3.2.1 版本的 Chart.js 和 3.0.0-beta.9 版本的 ng2-charts。我正在用这个版本升级一个项目。我从模拟数据开始,一切正常:图表按预期显示。

在我开始使用真实数据进行测试之前,我都是从后端获取的。轴、标签、图例未更新,图表未显示。

我在这里重现了这个问题: https://stackblitz.com/edit/chart-js-321-ng2-charts-300-beta9-rest?file=src%2Fapp%2Fapp.component.ts

HTML:

<canvas baseChart 
    [datasets]="barChartData" 
    [labels]="barChartLabels" 
    [options]="barChartOptions" 
    [legend]="barChartLegend" 
    [type]="barChartType">
</canvas>

TS:

    public barChartOptions: ChartOptions = {
        indexAxis: 'y',
        responsive: true,
        scales: {
          x: {
            min: 0
          }
        }
      };
      public barChartLabels: string[] = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
      public barChartType: ChartType = 'bar';
      public barChartLegend = true;
      public barChartPlugins = [];
      public barChartData: ChartDataset[] = [
        {
          data: [], //comment it out to see that chart loads with mock data below
          // data: [65, 59, 80, 81, 56, 55, 40],
          backgroundColor: 'green',
          label: 'Series A'
        },
        {
          data: [], //comment it out to see that chart loads with mock data below
          // data: [28, 48, 40, 19, 86, 27, 90],
          backgroundColor: 'red',
          label: 'Series B '
        }
      ];
    
      @ViewChild(BaseChartDirective, { static: true }) chart: BaseChartDirective;
ngOnInit() {
    //comment http out to see that chart loads with mock data above
    this.subscription = this.http
      .get('https://api.ratesapi.io/api/2020-05-10')
      .subscribe(data => {
        this.barChartData[0].data = [
          data.rates.GBP,
          data.rates.HKD,
          data.rates.IDR,
          data.rates.PLN,
          data.rates.DKK,
          data.rates.LVL,
          data.rates.INR
        ];
        this.barChartData[1].data = [
          data.rates.CHF,
          data.rates.MXN,
          data.rates.CZK,
          data.rates.SGD,
          data.rates.THB,
          data.rates.BGN,
          data.rates.MYR
        ];
        this.barChartLabels = ['1', '2', '3', '4', '5', '6', '7'];
        this.barChartData[0].label = 'Label1';
        this.chart.update();
      });
  }

这里我使用的是旧版本,一切正常: https://stackblitz.com/edit/chart-js-293-ng2-charts-232-rest?file=src%2Fapp%2Fapp.component.ts

【问题讨论】:

  • 请将相关代码作为代码块发布在您的问题中。如果(..when!!)链接死了,这个问题就变得毫无用处了。拥有堆栈闪电战很棒,但本身需要一些有问题的代码:)

标签: angular chart.js ng2-charts chart.js3


【解决方案1】:

https://github.com/valor-software/ng2-charts/issues/1313

代替图表。更新()暂时使用图表。渲染()。

编辑:在 ng2-charts@3.0.0-rc.2 中,此问题已解决。你可以使用 update() 甚至不使用 update() 方法。

【讨论】:

    猜你喜欢
    • 2021-11-08
    • 1970-01-01
    • 2016-05-27
    • 1970-01-01
    • 2020-08-31
    • 2018-07-24
    • 1970-01-01
    • 1970-01-01
    • 2015-05-16
    相关资源
    最近更新 更多