ng2-chart 折线图中仅显示第一个增加值

Only first value added gets displayed in ng2-chart linechart

我有一个非常简单的折线图,我想在用户单击按钮时在其中添加值。但无论出于何种原因,只会显示第一个添加的值(在初始值之后),之后的所有值都会被削减。

我知道 但我已经在使用标签,但它仍然无法正常工作。

我已经制作了我的问题的 plunkr 版本,但这里基本上是我的代码:

模板:

<div style="display: block">
    <canvas baseChart
            [options]="chartOptions"
            [data]="chartData"
            [labels]="chartLabels"
            [chartType]="chartType"></canvas>
</div>

<button (click)="addRandomValue()">Add Random value</button>

组件:

export class ChartComponent implements OnInit {
    public chartType: string;

    public chartData: number[];
    public chartLabels: string[];

    public chartOptions: any = {
        responsive: true,
        maintainAspectRatio: false
    };

    ngOnInit(): void {
        this.chartType = 'line';
        this.chartLabels = [ '1', '2', '3' ];
        this.chartData = [ 0, 10, 20 ];
    }

    addRandomValue(): void {
        this.chartData.push(Math.random() * 10 + 10);
        this.chartLabels.push(this.chartData.length + '');

        // weird workaround for refreshing data, works fine
        // for all other chart types I tried it on
        this.chartData = this.chartData.slice();
        this.chartLabels = this.chartLabels.slice();
    }
}

这是某种错误还是有人知道如何解决这个问题?

这是一个众所周知的问题。如果您查看 ng2-chart 的示例,您会注意到条形图声明下方的注释 (https://github.com/valor-software/ng2-charts/blob/master/demo/src/app/components/charts/bar-chart-demo.ts)。

简而言之,您必须克隆数据,在克隆上完成 CRUD,然后将数据重新分配给原始变量,以便识别更改。

删除标签部分,应该可以解决问题

这意味着您的 addRandomValue() 应该如下所示:

addRandomValue(): void {
    this.chartData.push(Math.random() * 10 + 10);
    this.chartLabels.push(this.chartData.length + '');

    // weird workaround for refreshing data, works fine
    // for all other chart types I tried it on
    this.chartData = this.chartData.slice();
}