Angular ChartJS 2.9.4 问题更新图表

Angular ChartJS 2.9.4 issue updating chart

我在 Angular 9+ 中更新图表(版本 2.9.4)时遇到问题,虽然我可以使用 new Chart(ctx, config) 创建新图表实例但无法更新它。我得到了 ERROR TypeError: chart.update is not a function

参考:https://www.chartjs.org/docs/2.9.4/developers/updates.html?h=update

下面是我的代码

ReportComponent.html

<canvas #chart style="width: 100%; height: 480px;">{{chart}}</canvas>

<button (click)="generateReport()">Generate</button>
<button (click)="updateReport()">Update</button>

ReportComponent.ts

export class ReportDashboardComponent implements OnInit, AfterViewInit  {
    @ViewChild('chart', { static: false }) chartRef: ElementRef;
    chart: Chart;
    dataSource: any;

    constructor(
        private reportService: ReportService,
    ) {}

    generateReport() {
        if ( this.dataSource ) {
          this.chart = this.reportService.init(this.chartRef, this.dataSource);
        }
    }

    updateReport() {
        if ( this.dataSource ) {
          this.reportService.update(this.chartRef, this.dataSource);
        }
    }
}

ReportService.ts

import { Chart, ChartConfiguration, ChartOptions, ChartData } from 'chart.js';

export class ReportService {
    chart: Chart;

    constructor() { }

    init(chartRef: ElementRef, data: UniChartData): Chart {
        const ctx = chartRef.nativeElement.getContext('2d');
        const config = this.getConfig(data);

        return new Chart(ctx, config);
    }

    update(chart: Chart, data: any): void {
        if (!chart) { return; }

        chart.config = this.getConfig(data);
        chart.update();
    }
}

我尝试了多种方法,但到目前为止都没有成功。如有任何帮助,我们将不胜感激。

提前致谢。

我认为您需要将图表对象而不是 ElementRef 传递给服务的更新函数,它应该可以工作...

updateReport() {
        if ( this.dataSource ) {
          this.reportService.update(this.chart, this.dataSource);
        }
    }