【发布时间】:2021-04-08 23:22:35
【问题描述】:
我需要在饼图中显示我的用户类型。 我正在使用 Angular2、Chart.js 和 ng2-charts。
dashboard.component.ts:
export class DashboardComponent implements OnInit {
employees = {};
public countFree : number = 0;
public countPaid : number = 0;
public chartData: Array<Object> = [];
public chartLabels: Array<Object> = [];
constructor(private dashboard: DashboardService) { }
ngOnInit() {
this.dashboard.fetchData('http://localhost:8080/employees').subscribe(res => {
res.forEach(function (eachObj) {
if(eachObj.usertype=='Free')
this.countFree++;
else
this.countPaid++;
}.bind(this));
this.chartLabels = ['Paid Users', 'Free Users'];
this.chartData = [{ data: [this.countPaid, this.countFree++] }];
});
}
}
dashboard.component.html:
<div style="width: 40%;">
<canvas
baseChart
[chartType]="'pie'"
[datasets]="chartData"
[labels]="chartLabels"
[options]="chartOptions"
[legend]="true"
</canvas>
</div>
我收到错误“TypeError:无法读取未定义的属性‘数据’”。 如果我将图表代码放在 fetchData() 之外,它可以正常工作。 但我需要将 countFree 和 countPaid 显示为图表数据。
需要别人的帮助。
【问题讨论】: