我正在使用 ng2-charts - https://github.com/valor-software/ng2-charts
我有一个饼图,如果我在 component.ts 文件顶部声明变量时对数据进行硬编码,就像我的饼图显示的示例一样。
但我显然想让饼图数据动态化。我可以通过服务调用数据(这是一个数字),将数字添加到数据数组中,饼图不起作用。但是如果我执行控制台日志,该数组会打印出我添加到其中的新数据/数字。
我需要以某种方式重新绘制表格。想不通。
public pieChartLabels:string[] = ['Red Flags','Green Flags'];
public pieChartData: number[] = [200, 400];
public chartType:string = 'pie';
public redFlagsTotal: any;
public greenFlagsTotal: any;
constructor(private dataService:flagService) {
let component = this;
this.redFlagsTotal = this.dataService.getRedFlags().then(function(result){
component.redFlagsTotal = result.length;
console.log(component.redFlagsTotal);
component.pieChartData.push(component.redFlagsTotal);
console.log(component.pieChartData);
});
this.greenFlagsTotal = this.dataService.getGreenFlags().then(function(result){
component.greenFlagsTotal = result.length;
console.log(component.greenFlagsTotal);
component.pieChartData.push(component.greenFlagsTotal);
console.log(component.pieChartData);
});
}
最佳答案
您可以像这样隐藏和显示图表一毫秒:
refreshChart(){
this.mychart.show = false;
setTimeout(()=>{
this.mychart.show = true;
},1);
}
在模板中使用 mychart.show
和 *ngIf
,如下所示:
<div style="display: block">
<canvas baseChart
*ngIf="mychart.show"
[data]="pieChartData"
[labels]="pieChartLabels"
[chartType]="pieChartType"
(chartHover)="chartHovered($event)"
(chartClick)="chartClicked($event)"></canvas>
</div>
在您的函数中,当您想要刷新图表时可以使用 refreshChart()
函数。
编辑:
如果你重新初始化数组而不是 char 应该自动更新,而不是这样:
component.pieChartData.push(component.greenFlagsTotal);
这样做:
let temp = [...component.pieChartData, ...component.greenFlagsTotal];
component.pieChartData = [...temp];
关于javascript - ng2 图表 - 刷新饼图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42414253/