I'm having some trouble loading JSON-data from an external API into a D3-graph. I'm using Quandl's API to load brent oil price-rates over a period of time, which is the data I'm trying to graph. I'm making use of Angular in my project, so I have a service set up to make the AJAX-call and then provide it to the scope. This I can do successfully as long as I don't try to involve my D3-code.
When I do, I get several errors:
GET http://localhost:3000/[object%20Object] 404 (Not Found)
and this:
Uncaught TypeError: Cannot read property 'forEach' of undefined
which is tied to some error in my d3-code I cannot well understand.
Here is the full code producing the errors:
app.service('oilService', function($http) {
delete $http.defaults.headers.common['X-Requested-With'];
this.getData = function() {
var URL = "https://www.quandl.com/api/v1/datasets/CHRIS/ICE_B1.json";
return $http({
method: 'GET',
url: URL
})
}})
.directive('oilGraph', function() {
return {
scope: {},
controller: function(oilService) {
var width = 200;
var height = 100;
var parseTime = d3.timeParse("%y-%m-%d");
var x = d3.scaleTime().range([0, width]);
var y = d3.scaleLinear().range([height, 0]);
var valueline = d3.line()
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.settle); });
var svg = d3.select("#oilgraph").append("svg")
.attr("width", width)
.attr("height", height);
oilService.getData()
.then(function(data) {
d3.json(data, function(error, data) {
if (error) {
console.log(error);
}
data.forEach(function(d) {
d.date = parseTime(d[0]);
d.settle = d[4];
})
x.domain(d3.extent(data, function(d) { return d.date; }));
y.domain([0, d3.max(data, function(d) { return d.settle; })]);
svg.append("path")
.data([data])
.attr("class", "line")
.attr("d", valueline);
svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
svg.append("g")
.call(d3.axisLeft(y));
})
})
}
}
})
(nevermind the curly brackets-mess)
dataindata.forEach(function(d) {...is undefined - due to the first error. Could you log the result ofoilService.getData()by putting a console.log here:.then(function(data) { console.log("data:", data)? Could you also post what the result ofconsole.log(error);is? (I am guessing it is the first error but just in case)http://localhost:3000/[object%20Object]. I mean this is not constructed anywhere in the code andd3.jsontakes as input thedatafromoilService.getData()so something there must be fishy..d3.json(url[, callback]). Your data object is interpreted as a file system uri.d3.jsonand load directly the data