【发布时间】:2021-03-17 10:30:27
【问题描述】:
我有一个服务器端脚本,它将传感器信息保存到数据库中。然后,此信息应显示在前端。前端是一个角度应用程序。数据库中的传感器信息将显示在基于冰沙包的图表中。在页面加载期间的前端,我在 ngOnInit 函数中调用 API 端点,并返回如下输出:
[
{
"id": 1,
"name": "CPU Usage",
"frequency": 5,
"unit": "%"
},
{
"id": 2,
"name": "Memory Usage",
"frequency": 4,
"unit": "GB"
}
]
然后我将它加载到一个数组中:
public charts: Chart[] = [];
constructor(private httpClient: HttpClient, private dataService: ApiService) { }
ngOnInit(): void {
this.httpClient.get<any>(this.dataService.baseUrl + '/measurable/active').subscribe({
next: data => {
for (let i = 0; i < data.length; i++) {
let smoothie = new SmoothieChart();
this.charts.push(new Chart(data[i].id, data[i].name, data[i].unit, smoothie));
}
console.debug(this.charts);
},
error: error => {
console.error('Could not load any measurable', error.message);
}
})
}
并在 ngFor 的帮助下在 html 中为冰沙显示一些必要的画布:
<div class="container">
<div class="row">
<div class="col-md-6 mx-auto">
<p>dashboard works!</p>
<div class="row" *ngFor="let chart of charts">
<label>{{ chart.name }}({{ chart.unit }})</label>
<canvas id="{{ chart.id }}" style="width:100%; height:200px" width="1262" height="200"></canvas>
</div>
</div>
</div>
</div>
在此加载过程中,我想在显示画布后对每个元素调用一个函数,该函数将初始化冰沙图以流式传输数据。
我不能使用ngAfterViewinit 函数,因为API 调用是异步的,它在请求返回数据之前执行。
我在somesimilarposts 中读到它,我可以创建一个指令来执行此操作,但很可能是由于缺乏角度知识,我无法理解和复制它(意思是:我明白了后面也复制了所有的代码,但都没有用)
谁能告诉我如何解决这个问题并解释其背后的逻辑,以便像我这样没有经验的人也能理解它?
【问题讨论】:
标签: angular typescript callback ngfor