我想使用角度 APEX 图表来可视化来自 API 的一些数据。由于数据获取需要一段时间,因此在加载数据之前图表会呈现为空图表。有没有办法重新渲染图表或在渲染图表之前等待数据?
//service component
import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { Observable } from "rxjs";
@Injectable({
providedIn: "root",
})
export class DataService {
constructor(private http: HttpClient) {}
datax: any;
xTime: any[] = [];
yValue: any[] = [];
getDayData(): Observable<any> {
let url = "http://localhost:4997/activepowerL1?DateTime=1620352800000";
return this.http.get(url);
}
}
// component.ts
constructor(private data: DataService) {
this.data.getDayData().subscribe((data) => {
this.data.datax = data;
console.log(this.data.datax[1].DateTime);
this.data.xTime = [];
this.data.yValue = [];
for (let dataelt of this.data.datax) {
this.data.xTime.push(String(new Date(new Date(dataelt.DateTime)).toISOString().slice(11, 16)));
this.data.yValue.push(parseFloat(dataelt.Value));
}
console.log(this.data.xTime);
});
}
```
```
//component.html
<div id="chart">
<apx-chart
[series]="chartOptions.series"
[chart]="chartOptions.chart"
[xaxis]="chartOptions.xaxis"
[dataLabels]="chartOptions.dataLabels"
></apx-chart>
</div>
```
我最近遇到了类似的重新渲染问题,找到了两种可能的解决方案:
使用 apexchart APi 中的 updateSeries:允许更新覆盖现有数组的系列数组
例如:
chart.updateSeries([{data: [{x: "02-02-2002",y: 44}, {x: "12-02-2002", y: 51}]}])
触发变更检测:更新数据源后,可以手动触发变更检测,以确保图表组件用新数据重新渲染
例如:
this.dataService.getChartData().subscribe((data) => { this.chartData = data; this.cdr.detectChanges(); });