0

I have structure API:

api: {
    users: {
        details: {},
        actions: {}
    },
    settings: {
        users: {}
    }
}

for example:

GET /api/users
return list of users

GET /api/users/1
return user with id 1

GET /api/users/1/details
return user deteils

GET /api/users/1/details/photo
return user fetail with alias photo

I wrote

.factory('userService', function($resource){
        return $resource('/api/users/:id/:items/:itemsId', {}, {
            query: { method: 'GET', isArray: false }
        });
    });

now I can do userService.query() and get list of users
but if I can`t do as this:

var users = userService.query();
users[1].name = 'newName';
users[1].save();

users[1] dont save edited info because users[1] dont have resourse methods, resourse methots isset only users.

And I can`t do as this:

var users = userService.query();
users[1].get('deteils');

How I can add resourse methods for all my structure?

  • possible duplicate of [How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – Stewie Nov 28 '13 at 07:17

1 Answers1

0

First of all you have to prefix instance methods with a $ sign, like users[1].$save().

Then why are you setting isArray to false but treat the result like an array?

You should also bind the id paramter to the id property of your user. I assume it is called id.

So you would do something like this:

.factory('userService', function($resource){
    return $resource('/api/users/:id/:items/:itemsId', { id: '@id' });
});

Note that you have to specify the parameters items and itemsId in your call, otherwise they will be left out. e.g.:

var users = userService.query();
users[1].name = 'newName';
// assume users[1].id===1
users[1].$save();
// will do a POST /api/users/1

users[1].$get({ items: 'details' });
// will do a GET /api/users/1/details

users[1].$get({ items: 'details', itemsId: 'photo' });
// will do a GET /api/users/1/details/photo

PS: Maybe you should also check if the default methods (listed here) fits your REST API, otherwise you should define your own.

kleinph
  • 151
  • 1
  • 9