Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding angularJS $resource isArray property

i'm learning angular's $resource service and in the angular tutorial a custom action is added (query) that has its method set to 'get' and isArray is set to true

return $resource('phones/:phoneId.json', {}, {
      query: {method:'GET', params:{phoneId:'phones'}, isArray:true}
 });

However, if you look at the docs for $resource the 'query' action already has its method set to 'get' and isArray is already set to true by default. So i thought that i can just leave those properties out.

This works for the method property, but it turns out that if i leave out the isArray property i get this error:

Error: [$resource:badcfg] Error in resource configuration for action query. Expected response to contain an object but got an array

Why is that?

like image 752
kevinius Avatar asked Feb 13 '15 11:02

kevinius


1 Answers

I think you have misunderstood the documentation.

By default without adding any custom actions, the following are supported:

'get':    {method:'GET'},
'save':   {method:'POST'},
'query':  {method:'GET', isArray:true},
'remove': {method:'DELETE'},
'delete': {method:'DELETE'} 

So by default the query action expects an array to be returned which makes sense since a query generally would return an array of items.

So if you use:

phonecatServices.factory('Phone', ['$resource', function($resource){
    return $resource('phones/phones.json');
}]);

You can then perform a query like so:

var queryParams = { name: 'test' };

Phone.query(queryParams, {}, function (response) {
    $scope.phones = response;
});

Now if you wanted to add a custom action then the default for isArray is false so:

return $resource('phones/:phoneId.json', {}, {
      someCustomAction: {method:'GET', params:{phoneId:'phones'} }
});

would need to return an object. If an array was returned then isArray would need to be set to true like so:

return $resource('phones/:phoneId.json', {}, {
      someCustomAction: {method:'GET', params:{phoneId:'phones'}, isArray: true }
});
like image 89
Wayne Ellery Avatar answered Sep 20 '22 15:09

Wayne Ellery