我使用 ng2charts 模块来渲染图表。如果我尝试使用以下虚拟数据,条形图会正确呈现。
打字稿
public barChartOptions: any = {
scaleShowVerticalLines: false,
responsive: true
};
public barChartLabels: string[] = ['Label1', 'Label2', 'Label3'];
public barChartType: string = 'bar';
public barChartLegend: boolean = true;
public barChartData: any[] = [
{ data: [65, 59, 80], label: 'Data1' },
{ data: [28, 48, 40], label: 'Data2' },
{ data: [30, 28, 80], label: 'Data3' }
];
组件 HTML:
<canvas style="height:230px" baseChart [datasets]="barChartData" [labels]="barChartLabels" [options]="barChartOptions" [legend]="barChartLegend" [chartType]="barChartType" (chartHover)="chartHovered($event)" (chartClick)="chartClicked($event)"></canvas>
但是,如果我尝试从服务器获取数据并动态设置数据,则无法按预期工作。
我得到以下错误
HomeComponent.html:73 错误类型错误:无法读取未定义的属性“数据”
请参考我下面的代码。
export class HomeComponent implements OnInit {
serverData: any;
public barChartOptions: any = {
scaleShowVerticalLines: false,
responsive: true
};
public barChartLabels: string[];
public barChartType: string = 'bar';
public barChartLegend: boolean = true;
public barChartData: any[];
constructor(private fb: FormBuilder, private Service: Service,
private route: ActivatedRoute, private router: Router, private _configService: ConfigService) {
this.getApis();
}
ngOnInit() {
const loggedInUser = new LoggedInUser();
const user = loggedInUser.getLoggedUser();
if (user != null) {
this.loggedInUserId = loggedInUser.getLoggedUser().UserId;
}
}
getApis() {
this._configService.get()
.subscribe(c => {
this.apiEndpoints = c;
this.loadDashBoardDetails();
},
error => { this.msg = <any>error; });
}
loadDashBoardDetails() {
this.indLoading = true;
this.Service.get("APIENDPOINT")
.subscribe(c => {
this.serverData = c[0];
this.loadserverData();
this.indLoading = false;
},
error => {
this.msg = <any>error;
}
);
}
loadserverData() {
let chartData: any[];
let data1 = '';
let data2 = '';
let data3 = '';
this.barChartLabels = new Array<string>();
chartData = new Array<any>();
for (let _i = 0; _i < this.serverData.length; _i++) {
this.barChartLabels.push(this.serverData[_i].Code);
if (data1 === '') {
data1 = this.serverData[_i].Target;
} else {
data1 = data1 + ',' + this.serverData[_i].data1;
}
if (data2 === '') {
data2 = this.serverData[_i].data2;
} else {
data2 = data2 + ',' + this.serverData[_i].data2;
}
if (data3 === '') {
data3 = this.serverData[_i].data3;
} else {
data3 = data3 + ',' + this.serverData[_i].data3;
}
}
chartData.push({
data: data1,
label: 'data1 label'
});
chartData.push({
data: data2,
label: 'data2 label'
});
chartData.push({
data: data3,
label: 'data3 label'
});
this.barChartData = chartData;
}
}