Chartjs-Save data from REST API Get method and use it one more time

0👍

getSensorValues() is returning an observable, so you need to subscribe to it to do the API call. The execution of the subscribe is asynchronous, because the api calls can take 10 ms, 1 second or 1 minut, this is not predictible (that’s why we are using observable here).

So every things you want to do with the received data from obervabe must be handled in the subscription. Be aware of that because sometimes, the asynchronous execution will be fast and you will think an execution outside of the subscription is working, but if the execution is slower for some reason another time, you will have an unwanted behavior.

I will give you 2 tips :

  • split your code, move the execution you want in on or more separated functions
  • do not use code in the subscribe() method, use pipe with appropriate operators instead
ngOnInit() {
    this.DataService.getSensorValues().pipe(
        tap(data => createChartFromData(data)),
        catchError(error => {
             console.log(error);
             return of();
        })
    )
    .subscribe()
}

createChartFromData(data) {
      this.sensorsValues = data;

      let i = 0;
      let j = 0;
      while( i < this.sensorsValues.length) {
        if(this.sensorsValues[i].kindOfSensor == 'Exposure') {
          this.YValue.push(this.sensorsValues[i].y);
          this.XValue.push(j);
          j = j + 1;
        }
        i = i + 1;
      }

      let myChart = new Chart("myChart2", {
        type: 'line',
        data: {
            labels: this.XValue,
            datasets: [{
                label: 'Exposure',
                data: this.YValue,
                borderWidth: 1
            }]
      })    
}

Leave a comment