I'm getting a strange behaviour with AngularJS's $http and not really understanding how transformResponse works (the docs are a bit light on this one).
WebAssets.get = function () {
return $http.get('/api/webassets/list', {
transformResponse: [function (data, headersGetter) {
// not sure what to do here?!
return data;
}].concat($http.defaults.transformResponse) // presume this isn't needed, added for clarity
}).then(function (response) {
return new WebAssets(response.data);
});
};
The api returns an array of objects:
[{"webasset_name": "...", "application_id": "...", "etc": "..."}, ... ]
But when transformResponse has done it's evil business the data has transformed into an indexed object:
{"0":{"webasset_name":"...","application_id":"...", "etc": "..."}, "1":....}
I want to keep the original data structure (an array of objects).
I'm getting a strange behaviour with AngularJS's $http and not really understanding how transformResponse works (the docs are a bit light on this one).
WebAssets.get = function () {
return $http.get('/api/webassets/list', {
transformResponse: [function (data, headersGetter) {
// not sure what to do here?!
return data;
}].concat($http.defaults.transformResponse) // presume this isn't needed, added for clarity
}).then(function (response) {
return new WebAssets(response.data);
});
};
The api returns an array of objects:
[{"webasset_name": "...", "application_id": "...", "etc": "..."}, ... ]
But when transformResponse has done it's evil business the data has transformed into an indexed object:
{"0":{"webasset_name":"...","application_id":"...", "etc": "..."}, "1":....}
I want to keep the original data structure (an array of objects).
Share Improve this question asked Aug 9, 2013 at 12:53 Rob BRob B 1,5233 gold badges23 silver badges38 bronze badges 2- You might want to have a look here: stackoverflow.com/questions/17134401/… – AlwaysALearner Commented Aug 9, 2013 at 13:02
- They are using $resource, I'm using $http – Rob B Commented Aug 9, 2013 at 15:07
3 Answers
Reset to default 14To get angular to not convert your data into an object you need to override the behavior of the default $httpProvider.defaults.transformResponse. It is actually an array of transformers.
You could just set it to be empty: $http.defaults.transformResponse = [];
Here is an example transformer I have used to convert 64-bit long ints to strings:
function longsToStrings(response) {
//console.log("transforming response");
var numbers = /("[^"]*":\s*)(\d{15,})([,}])/g;
var newResponse = response.replace(numbers, "$1\"$2\"$3");
return newResponse;
}
To add a transformer to the default list, say ahead of the JSON deserializer, you can do this:
$http.defaults.transformResponse.unshift(longsToStrings);
Resource 0: "f" 1: "a" 2: "l" 3: "s" 4: "e" This finally worked for me:
transformResponse: function (data, headersGetter) {
return { isCorrect: angular.fromJson(data) }
}
Try using resource query method
https://github.com/angular/angular.js/issues/6314