Laurent
Laurent

Reputation: 987

Correct pattern using Angular $resource to get related data

I understood that the concept of $resource in AngularJS is to return

I am using a backend which does not provide all needed information in one shot.

For example: /User/:id

user = User.get({id: userId}); returns a User. Great.

If I need to get the number of his friends, I have another request wich will be like:

/User/:id/count=friend

And return:

{ count: 17 }

Here I am stuck, I can't use my user variable, or I will lose my user object. Plus the result will be a number, which does not represent my user anymore.

The 'dirty' way would be to go back with $http for this and to assign the result to user.friendsNumber = data.count.

But still not clean, if I user.$put() something, I lose my user.friendsNumber as it will be reassigned.

What is the correct way to handle this properly?

Upvotes: 0

Views: 112

Answers (1)

Dylan
Dylan

Reputation: 4773

You can specify the action like so, and I believe additional parameters just become regular get variables.

angoApp.factory('User', function($resource) {
  return $resource('/User/:id', {
    id: '@id'
  }, {
    countFriends: {
      method: 'GET',
      params: {
        count: 'friends'
      }
    }
});

...

User.$countFriends({id:123});
//This should call /User/123?count=friends

Upvotes: 2

Related Questions