Reputation: 81
I'm creating a chart using Highcharts (and getting the data from a JSON file). However, I'm getting TypeError: Cannot read property 'map' of undefined
.
I have the following code:
myData.get(function (data) {
$scope.loadData = data;
});
$('#container').highcharts({
xAxis: {
type: 'datetime'
},
series: [{
name: 'Temperature',
data: $scope.loadData.map(function(d) {
return [d.timestamp, d.actual];
})
}, {
name: 'Range',
data: $scope.loadData.map(function(d) {
return [d.timestamp, d.min, d.max];
}),
type: 'arearange'
}]
});
I've also created a Plunker.
Any tips on what I'm doing wrong here?
Upvotes: 1
Views: 17380
Reputation: 4142
So I changed your Plunkr to a working example: http://plnkr.co/edit/Q4z6NdVtp3TRMKgmH5tc?p=preview
First of all, in your data.json you have timestamps added as strings. Highchart does not accept that.
I changed the factory to get JSON data via $http
.factory('myData', function($http) {
return {
getData : function () {
var data = [];
data = $http.get('data.json');
return data;
}
}
})
In the callback of getData I build the chart:
myData.getData().then(function(response) {
$scope.loadData = response.data;
$('#container').highcharts({
xAxis: {
type: 'datetime'
},
series: [{
name: 'Temperature',
data: [$scope.loadData.timestamp, $scope.loadData.actual]
},
{
name: 'Range',
data: [$scope.loadData.timestamp, $scope.loadData.min, $scope.loadData.max],
type: 'arearange'
}]
});
});
Upvotes: 3
Reputation: 4708
this is asynchronous call :
myData.get(function (data) {
console.log("myData.Get");
$scope.loadData = data;
});
So $('#container').highcharts({...
will run before the data is set $scope.loadData = data;
you have to move the code inside the callback of myData
myData.get(function (data) {
$scope.loadData = data;
$('#container').highcharts({
xAxis: {
type: 'datetime'
},
series: [{
name: 'Temperature',
data: $scope.loadData.map(function(d) {
return [d.timestamp, d.actual];
})
}, {
name: 'Range',
data: $scope.loadData.map(function(d) {
return [d.timestamp, d.min, d.max];
}),
type: 'arearange'
}]
});
});
Upvotes: 0