I am trying to use Angular's transformResponse aspect of $http to convert XML data to JSON. The resulting object is null, and I can't figure out why.
Here is the $http request which is inside a service:
myApp.service('dataSource', function ($http) { // gets the XML data, turns it into JSON
this.getData = function(callback) {
$http.get('http://localhost:1337/testXML.xml', {transformResponse: function (data) {
var json = x2js.xml_str2json(data);
return json;
}
}
).
success(function (data) {
callback(data);
}).
error (function () {
alert("HTTP error.");
});
}
});
The callback function is defined in the controller, which is in a separate file. Here is the code:
// callback function
setData = function(data) {
$scope.dataJSON = data;
}
dataSource.getData(setData);
So the variable 'json' that is being returned by the call to $http is undefined. I have tried multiple different transformers, with no success. Can anyone spot my problem?
Thanks!
Your code looks fine. Inspect the json to see what you are getting either by adding a console.log(json) before the return line or by using the debugger (Chrome Dev Tools/Firefox) and setting breakpoints on the return line and inside the success function. Add json and data as watch variables in your debugger and you can inspect the values as you walk through each line.
Since you say that data is OK, and x2js is a rock-solid library, I'm going to guess that the json will be OK too when it gets to your success callback function. You can just step through the debugger and inspect the value as it passes from one to the other. Since it's asynchronous, you'll need to set a breakpoint in your success function.
It's possible that upon inspection, you'll find data is not really OK and that's what's causing the problems downstream.
I had null
returned when the namespace url had an errant space.
This was ok:
<fs:resultSource xmlns:fs="http://a9.com/-/opensearch/extensionsfiederation/1.0/" fs:sourceld="EDL">EDL</fs:resultSource>
but this was returned null:
<fs:resultSource xmlns:fs="http://a9.com/- /opensearch/extensionsfiederation/1.0/" fs:sourceld="EDL">EDL</fs:resultSource>