superjim
superjim

Reputation: 81

Integrating Highcharts with REST API

I'm studying AngularJS and I'm trying to integrate a chart using Highcharts and a REST API.

However, I'm not able to fetch the data:

$scope.myData = function() {

  Charts.query({
    id: $scope.currentState.id, 
    name: $scope.currentState.name
  }, 
  function(data) {
    $scope.charts = data;
  });

};

$('#chart').highcharts({
    title: {
        text: ''
    },
    xAxis: {
        categories: $scope.charts.timestamp
    },
    yAxis: {
      title: {
        text: 'test'
      }
    },
    series: [{
        data: $scope.charts.value
    }]
});

The first part connects to the REST API and the second generates the chart. Currently, I'm getting the following error: TypeError: Cannot read property 'value' of undefined.

Please, can someone help me?

Update: full code (http://plnkr.co/edit/ZgrDmKArfxFrMoAEFoTc) and JSON (http://pastebin.com/TX2pLHHe).

Upvotes: 1

Views: 2168

Answers (1)

Gustavo Hoirisch
Gustavo Hoirisch

Reputation: 1657

Your code runs synchronously in the controller however the data is coming in asynchronously. When you call the $('#chart').highcharts(...) function your data has not yet arrived so $scope.charts is not defined which is why you get a "cannot read 'value' of undefined" error ($scope.charts = undefined, so it has no value property!).

You need to call the highcharts function in the callback of the query. For example (this is untested by the way):

$scope.myData = function() {

  Charts.query({
    id: $scope.currentState.id, 
    name: $scope.currentState.name
  }, 
  function(data) {
    $scope.charts = data;
    drawChart(); // <= this is when you invoke the drawing of the chart because data has finally arrived!
  });

};

var drawChart = function(){ 
    $('#chart').highcharts({
        title: {
            text: ''
        },
        xAxis: {
            categories: $scope.charts.timestamp
        },
        yAxis: {
          title: {
            text: 'test'
          }
        },
        series: [{
            data: $scope.charts.value
        }]
    });
}

Upvotes: 1

Related Questions