9

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?

3
  • Did you remove query from $resource? return $resource('phones/:phoneId.json'); Commented Feb 13, 2015 at 11:45
  • no, i just removed the method property and i want to remove the isArray property but that doesn't work Commented Feb 13, 2015 at 12:04
  • 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 work Commented Feb 13, 2015 at 12:06

1 Answer 1

17

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 }
});
Sign up to request clarification or add additional context in comments.

1 Comment

To be fair, it's REALLY EASY to misunderstand Angular's documentation. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.