У меня есть две функции в Angular:
Одна для получения данных из веб-службы и сохранения их в переменных 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'}));
});
});
}
и один для создания диаграммы js с данными из this.apiDay
и this.apiDayLabel
:
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
Или что лучше всего делать в этом случае?