Understanding angularJS $resource isArray property
Asked Answered
M

1

8

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?

Maximalist answered 13/2, 2015 at 11:29 Comment(3)
Did you remove query from $resource? return $resource('phones/:phoneId.json');Arrack
no, i just removed the method property and i want to remove the isArray property but that doesn't workMaximalist
But why are your creating/replacing a custom query action as there is already one built in? Use the code I posted and the query will workArrack
A
16

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 }
});
Arrack answered 13/2, 2015 at 12:20 Comment(1)
To be fair, it's REALLY EASY to misunderstand Angular's documentation. :)Drusilla

© 2022 - 2024 — McMap. All rights reserved.