我正在我的 ionic 2 应用程序中使用 chart.js 如果我在没有 ngSwitch 条件的情况下实现用于渲染的画布元素,它可以正常工作,但是当我使用条件时,我遇到错误,本机元素未定义,因此画布元素未呈现,因为在订阅图表数据时画布元素尚未准备好。 我该如何解决这个问题。
@ViewChild('todayChart') todayChart;
@ViewChild('yesterdayChart') yesterdayChart;
ionViewWillEnter() {
this.homeauth.todaychart().subscribe((table) => {
var labels = [], datay = [], datum = [], timestamp = [];
for (var i = 0; i <= table.length - 1; i++) {
datum.push(table[i].chartdate);
labels.push(table[i].z10s3);
datay.push(table[i].z10s6);
timestamp.push(table[i].timestamp);
}
this.heutechart = new Chart(this.todayChart.nativeElement, {
type: 'line',
data: {
xLabels: labels,
datasets: [
{
label: 'G.Oil', fill: true, lineTension: 0.1, backgroundColor: "rgba(75,192,192,0.4)", borderColor: "rgba(75,192,192,1)",
pointHoverBorderWidth: 2, pointRadius: 1, pointHitRadius: 10, data: datay, spanGaps: false,
}
],
},
});
});
this.homeauth.yesterdaychart().subscribe((table) => {
var labels = [], datay = [], datum = [];
for (var i = 0; i <= table.length - 1; i++) {
datum.push(table[i].chartdate);
labels.push(table[i].z10s3);
datay.push(table[i].z10s6);
}
this.vortagschart = new Chart(this.yesterdayChart.nativeElement, {
type: 'line',
data: {
xLabels: labels,
datasets: [
{
label: 'G.Oil', fill: true, lineTension: 0.1, backgroundColor: "rgba(75,192,192,0.4)", borderColor: "rgba(75,192,192,1)",
pointHoverBorderWidth: 2, pointRadius: 1, pointHitRadius: 10, data: datay, spanGaps: false,
}
],
}
});
});
}
html:
<ion-segment [(ngModel)]="category">
<ion-segment-button value="today"> 24h </ion-segment-button>
<ion-segment-button value="yesterday"> 48h </ion-segment-button>
</ion-segment>
<div [ngSwitch]="category">
<div *ngSwitchCase="'today'">
<canvas #yesterdayChart> </canvas>
</div>
</div>
<div [ngSwitch]="category">
<div *ngSwitchCase="'yesterday'">
<canvas #todayChart></canvas>
</div>
</div>
您
不必为每种情况使用ng-switch
。
应该是这样的:
<div [ngSwitch]="category">
<div *ngSwitchCase="'today'"> <!-- case 1 -->
<canvas #yesterdayChart> </canvas>
</div>
<div *ngSwitchCase="'yesterday'">
<canvas #todayChart></canvas> <!-- case 2 -->
</div>
</div>
在组件中添加 if 条件,因为 DOM 中仅存在其中一个元素。
if(this.todayChart){
this.heutechart = new Chart(this.todayChart.nativeElement, {
type: 'line',
data: {
xLabels: labels,
datasets: [
{
label: 'G.Oil', fill: true, lineTension: 0.1, backgroundColor: "rgba(75,192,192,0.4)", borderColor: "rgba(75,192,192,1)",
pointHoverBorderWidth: 2, pointRadius: 1, pointHitRadius: 10, data: datay, spanGaps: false,
}
],
},
});
});
}
//Similarly for yesterdayChart