Search code examples
javascriptangularhighchartsangular2-highcharts

setData is not a function + Angular2-Highcharts


I was following simple example to set data to Highcharts using this Angular2-Highcharts module

As shown in the following example, i have made small tweak to dynamically set data to Highcharts. Following is the code snippet :

constructor() {
    this.options = {
      chart: { type: 'spline' },
      title: { text : 'dynamic data example'},
      series: [{ data: [2,3,5,8,13] }]
    };

    setTimeout(() => {
      this.chart.series[0].setData([21,31,51,81,13]);
    }, 3000);

    setTimeout(() => {
      this.chart.series.push({data:[]});
      this.chart.series[1].setData([100,200,300]);
    }, 5000);
}

Plunker link for the same .

Error :

ERROR TypeError: _this.chart.series[1].setData is not a function
    at eval (run.plnkr.co/QZBbWi3BVy3DeOzT/app/main.ts!transpiled:28)

My Observation :

What is evident with that error is there is no setData function in the series array in the 1st element. Alternate approach to resolve this is, initializing this.options with empty object with data property :

constructor() {
        this.options = {
          chart: { type: 'spline' },
          title: { text : 'dynamic data example'},
          series: [{ data: [2,3,5,8,13] },
                   { data: [] },
                  ]
        };
}

This is very crude way as i need to do the same for 50 elements in this.options.series if i see them coming dynamically

Is there any efficient and better approach to resolve this error ?

PS : Am new to Highcharts, so please bear with me if am doing something completely wrong at basic level.


Solution

  • setData modifies a series which already exists - if you do not have the series you cannot modify it.

    If you want to add a new series, you should use chart.addSeries() method like this:

       setTimeout(() => {
          this.chart.addSeries({
              data: [21,31,51,81,13]
          });
        }, 5000);
    

    example: http://plnkr.co/edit/61IgH8t3YKjtIOgzpUPB?p=preview