Search code examples
angularhighchartshighcharts-ng

Highcharts load series data problem in Angular


I'd like to display ECG signals. My data array: [ [time,value], [time2, value2] etc... ], but it's not the array that the essential. The problem is that I cannot access my data array in setInterval, so my chart options:

   this.chartOptions = {
      series: [
        {
          type: 'line',
          data: this.data,
        },
      ],
      chart: {
        events: {
          load: function () {
            var series = this.series[0];
            setInterval(function () {
              this.data.push(this.addMoreData()); //push new [time,value]
              const time = this.data[this.data.length - 1][0]; // get new time
              const value = this.data[this.data.length - 1][1]; // get new value
              var x = time,
                y = value;
              series.addPoint([x, y], true, true);
            }, 1000);
          },
        },
      }
    };

I got this error: 'TypeError: Cannot read property 'push' of undefined' because cannot access the data array. But if I change function () {} to () => {} and in this case also change this.series[0] to this.chartOptions.series[0]:

chart: {
        events: {
          load:  () => { // change
            var series = this.chartOptions.series[0]; // change
            setInterval( () => { // change
              this.data.push(this.addMoreData()); //push new [time,value]
              const time = this.data[this.data.length - 1][0]; // get new time
              const value = this.data[this.data.length - 1][1]; // get new value
              var x = time,
                y = value;
              series.addPoint([x, y], true, true);
            }, 1000);
          },
        },
      }

In this case I access the array but error: TypeError: series.addPoint is not a function. So how can I update my series? Here is my full code: https://stackblitz.com/edit/highcharts-ecg


Solution

  • You can use IIFE to store a reference to a component in a higher scope and use 'double' context in a returned function.

    Example:

        events: {
          load: (function(component){
            return function(){
              console.log(this, component); // chart, component
            }
          })(this)
        }
    

    Live demo: https://stackblitz.com/edit/highcharts-ecg-pqkkb9