I've encountered an issue with getting my chart to display properly. I am working on creating a chart using ng2-charts, where I retrieve data from a service and then display it on the chart. The problem arises when the data is not correctly displayed unless I insert an alert() function between fetching the data from the service and setting it on the chart.
lightData: LightData[];
public lineChartData = Array<any>();
public lineChartLabels = Array<any>();
ngOnInit() {
this.lightData = []; // Array initialized as empty
this.loadAll(); // Fetch all the data
this.setChartData(); // Set the data on the chart
}
loadAll() {
this.lightDataService.query().subscribe(
(res: Response) => this.onSuccess(res.json(), res.headers),
(res: Response) => this.onError(res.json())
);
}
public setChartData(){
for(let i = 0; i < this.lightData.length; i++)
{
this.lineChartLabels.push(this.lightData[i].id);
this.lineChartData.push(this.lightData[i].value);
}
}
private onSuccess(data, headers) {
for (let i = 0; i < data.length; i++) {
this.lightData.push(data[i]);
}
}
private onError(error) {
this.alertService.error(error.message, null, null);
}
The code doesn't work as expected - the chart remains empty. However, inserting an alert like this:
ngOnInit() {
this.lightData = []; // Array initialized as empty
this.loadAll(); // Fetch all the data
alert("blabla"); // Alert to pause execution
this.setChartData(); // Set the data on the chart
}
Makes it work! Strange how adding an alert resolves the issue. I've faced similar problems before with other functions and struggled to find a permanent fix.
Edit 1: I attempted to call the setChartData function within the asynchronous loadAll method:
lightData: LightData[];
public lineChartData = Array<any>();
public lineChartLabels = Array<any>();
ngOnInit() {
this.lightData = []; // Array initialized as empty
this.loadAll(); // Fetch all the data
}
loadAll() {
this.lightDataService.query().subscribe(
(res: Response) => {
this.onSuccess(res.json(), res.headers);
this.setChartData();
},
(res: Response) => this.onError(res.json())
);
}
public setChartData(){
for(let i =0; i < this.lightData.length; i++)
{
this.lineChartLabels.push(this.lightData[i].id);
this.lineChartData.push(this.lightData[i].value);
}
}
private onSuccess(data, headers) {
for (let i = 0; i < data.length; i++) {
this.lightData.push(data[i]);
}
}
private onError(error) {
this.alertService.error(error.message, null, null);
}
Unfortunately, this approach still does not resolve the issue.