我在Angular中有两个功能:
从Web服务获取一些数据并将其存储在this.apiDay
和this.apiDayLabel
变量中:
getDayScan() {
this.btcPriceService.getDailyBTCScan().subscribe(data => {
data.Data.Data.forEach(price => {
this.apiDay.push(price.open);
this.apiDayLabel.push(new Date(price.time * 1000).toLocaleTimeString([], {hour: '2-digit', minute: '2-digit'}));
});
});
}
并且使用this.apiDay
和this.apiDayLabel
中的数据创建一个chartjs:
public createDay(defaultChartConfig: any) {
this.canvas = document.getElementById('dayChart');
this.ctx = this.canvas.getContext('2d');
const dataTotal = {
// Total Shipments
labels: this.apiDayLabel,
datasets: [{
label: 'Price',
fill: true,
backgroundColor: this.bgColorSelector(this.apiDay),
borderColor: this.borderColorSelector(this.apiDay),
borderWidth: 2,
borderDash: [],
borderDashOffset: 0.0,
pointBackgroundColor: this.borderColorSelector(this.apiDay),
pointBorderColor: 'rgba(255,255,255,0)',
pointHoverBackgroundColor: this.borderColorSelector(this.apiDay),
pointBorderWidth: 20,
pointHoverRadius: 4,
pointHoverBorderWidth: 15,
pointRadius: 0,
data: this.apiDay,
}]
};
this.myChartDay = new Chart(this.ctx, {
type: 'lineWithLine',
data: dataTotal,
options: defaultChartConfig
});
}
我在ngOnInit()
函数中这样调用这两个函数:
ngOnInit() {
this.getDayScan();
this.createDay(defaultChartConfig);
}
我的问题是图表是在我从api获取数据之前创建的。
是否有办法等待数据在那里然后开始创建图表?
像这样(伪代码)
public createDay(defaultChartConfig: any) {
getDayScan();
// wait for it to finish so every necessary variable is declared
// and only THEN go on with the other code
this.canvas = document.getElementById('dayChart');
this.ctx = this.canvas.getContext('2d');
...
}
所以我只需要在createDay
中调用ngOnInit
函数
或者在这种情况下最佳做法是什么?
我建议您使用async
await
等待api响应。