The following JSON response from the server
[
"hello",
"world"
]
is being parsed into a 2d array by this ngResource service
myService.factory('Name', function($resource){
return $resource(site_url+'api/accounts/:accountId/names/', {}, {
list: {method:'GET', params:{}, isArray:true}
});
});
called like so
$scope.names = Name.list({accountId:$scope.account.id}, function(e){
console.log(e);
});
traces to
[{"0":"h","1":"e","2":"l","3":"l","4":"o"},{"0":"w","1":"o","2":"r","3":"l","4":"d"}]
Any hints?
TLDR; ngResource expects an object or an array of objects in your response.
When
isArrayis set totruein the list of actions, the ngResource module iterates over each item received in the response and it creates a new instance of a Resource. To do this Angular performs a deep copy between the item received and theResourceclass, which gives us an object with special methods ($save,$deleteand so on)Check the source here.
Internally angular uses angular.copy to perform the deep copy and this function only operates with objects and arrays, when we pass a string, it will treat it like an object.
Strings in JS can behave as arrays by providing sequential access to each character.
angular.copywill produce the following when passed a stringEach character becomes a value in an object, with its index set as the key. ngResource will provide a resource with properties
0and1.Your choices are:
Use the lower level $http service
Return an array of objects in your json response
Intercept the response and change your data
If you cannot modify the data the server sends back and want to use ngResource you will need to transform the response. Read how to do it here