Chartjs-Problem creating chart out of GET request with Angular

0👍

The problem is that you’re not awaiting for the http call to return the actual data.
Change the method getSimulation to look like this:

async getSimulation(id: string): Promise<void> {
  try {
    this.currentSimulation = await this.controllerService.get(id).toPromise();
    console.log('current simulation data retrieved successfully', this.currentSimulation);
  } catch (error) {
    console.error('error retrieving current simulation', error);
  }
}

And then also do this adjustments to ngOnInit().

async ngOnInit(): Promise<void> {
  var id = this.route.snapshot.params['id'];
  await this.getSimulation(id);
  .............................
}

This should do the trick.


By the way, I don’t know what version of angular you’re using, that’s why I used .toPromise() for casting from Observable to Promise. However on the recent versions of Angular (IIRC Angular 11+), lastValueFrom is the one to use, since .toPromise() was deprecated and will be removed sooner than later.

So getSimulation would ideally look like this:

async getSimulation(id: string): Promise<void> {
  try {
    this.currentSimulation = await lastValueFrom(this.controllerService.get(id));
    console.log('current simulation data retrieved successfully', this.currentSimulation);
  } catch (error) {
    console.error('error retrieving current simulation', error);
  }
}

Leave a comment