0

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

  • A resource, an object representing this resource (get, update, delete)
  • A list of objects representing this resource (query)

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?

1
  • Declare a custom action ? $resource(url, [paramDefaults], [actions], options); Commented Oct 30, 2014 at 8:39

1 Answer 1

2

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

2 Comments

No problem for adding custom actions and doing requests, this is currently what I am doing. But I feel like this is not clean. What I am interested is to assign more properties like countFriend to a parent user ressource (already resolved), which I am sometimes updated, so losing properties I newly assigned like countFriend.
So it sounds more like you're looking for persistence like local storage? Resource manages a CRUD, but maintaining the response data is just a matter of how you handle that object.

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.