ng2-charts 更新标签和数据
我正在尝试使用 ng2-chart 动态创建图表,我从 angular 2 服务中获取信息,当我只更改图表的标签时它工作,当我更改数据时它只工作,但是当我同时更改时,图表中的数据都会更新.请任何人解释这种奇怪的行为.
I'm trying to create dynamically a chart using ng2-chart, I get information from an angular 2 service, when I change only labels of chart it works and when I change data only it works, but When I change both just data are updated in the chart. have any one an explication for this strange behavior.
我的模板:
<canvas baseChart height="130" width="180"
[data]="doughnutChartData"
[labels]="doughnutChartLabels"
[chartType]="doughnutChartType"
(chartHover)="chartHovered($event)"
(chartClick)="chartClicked($event)">
</canvas>
我的班级:
export class PlDoughnutComponent implements OnInit {
constructor(private homeService: TileServiceService) { }
ngOnInit() {
this.updatePLdoughnut();
}
public util : UtilService = new UtilService();
public doughnutChartLabels:string[] = ['Download Sales'];
public doughnutChartData:number[] = [0,0,100];
public doughnutChartType:string = 'doughnut';
public updatePLdoughnut(){
this.homeService.getTile().
then(res => {
this.doughnutChartLabels = res.PLtypes;
this.doughnutChartData = this.util.objectToIntArray(res.PLByTypes);
})
}
}
推荐答案
显然,如果您不修改对标签数组的原始引用,它似乎可以工作,至少对我来说是这样.我的意思是,如果你想要一组完全不同的标签,你应该这样做:
Apparently, if you do not modify the original reference to the labels array, it seems to work, at least for me. I mean, if you want a completely different set of labels, you should do something like this:
在模板中:
<canvas baseChart
[datasets]="lineChartData"
[labels]="lineChartLabels"
[options]="lineChartOptions"
[chartType]="'line'"></canvas>
在ts组件中:
this.lineChartLabels.length = 0;
for (let i = tempLabels.length - 1; i >= 0; i--) {
this.lineChartLabels.push(tempLabels[i]);
}
或者,使用新的 ECMAScript 语法:
Or, using new ECMAScript syntax:
this.lineChartLabels.length = 0;
this.lineChartLabels.push(...tempLabels);
关键可能是 this.lineChartLabels.length = 0;
语句,它实际上通过将数组长度设置为 0 来清空"您的数组,而无需修改引用.希望这会有所帮助!
The key is maybe the this.lineChartLabels.length = 0;
statement, which practically 'empties' your array by setting its length to 0, without modifying the reference.
Hope this helps!
相关文章