23

from the documentation (http://docs.angularjs.org/api/ngResource.$resource):

$resource(url[, paramDefaults][, actions]);

paramDefaults(optional) – {Object=} – Default values for url parameters. ... If the parameter value is prefixed with @ then the value of that parameter is extracted from the data object.

The question is what data object do they refer to? How to use this feature?

akonsu
  • 28,824
  • 33
  • 119
  • 194

1 Answers1

7

lets say you have a resource like this:

var User = $resource('/user/:userId', {userId:'@id'});
var user = User.get({userId:123});

It means that the value of :userId in your url will be replaced with the id property from the user object when that property is required.

So when is it required? Its required when you are doing something to an existing user, like geting one, updating one. It is not required when you create a user.

In most cases, you will want to have at least one param prefixed with @ in your REST url that resource uses (probably the object id). If you dont have one, that means that in order for you to save an instance of an object, you dont need to know anything about where its stored. This implies that its a singleton object. Maybe like a settings object.

Here is your long awaited example:

var User = $resource('/user/:userId/:dogName', {userId:'@id', dogName:@dog});
User.get({userId:123, dog:'Matt'}, function() { .. })

will produce the request: GET /user/123/Matt

mkoryak
  • 57,086
  • 61
  • 201
  • 257
  • 19
    This answer (specifically the example in it) fails to explain the purpose of '@id'. A better answer is found here: [What is @id as passed to $resource?](http://stackoverflow.com/questions/17559515/what-is-id-as-passed-to-resource). – Stewie Aug 06 '13 at 21:19
  • 2
    And it makes the same mistake as the AngularJS docs, saying things like "...will be replaced with the id property from the user object..." Where is 'id' in the user object? – Ted M. Young Jun 18 '14 at 00:46
  • According to @Stewie link, the default parameter `@id` it's because you can do `User.id = 123;` and later `var user = User.get({});` – Jaider Jul 07 '14 at 05:29
  • 2
    Why not `User.get({id:123, dog:'Matt'}, function() { .. })`? – arve0 Oct 05 '15 at 08:27