I have two functions in Angular:
One to get some data from a web service and store it in the this.apiDay and this.apiDayLabel variable:
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'}));
});
});
}
and one to create a chartjs with the data from this.apiDay and 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
});
}
I call these two functions in the ngOnInit() function like this:
ngOnInit() {
this.getDayScan();
this.createDay(defaultChartConfig);
}
My problem is that the chart is created before I have my data from the api.
Is there a way to wait for the data to be there and then start creating the chart?
Like so (Pseudocode)
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');
...
}
So I have to call only the createDay function in the ngOnInit
Or what is best practice in this case?
this.createDay(defaultChartConfig);insidethis.getDayScan();when you got response from api.