Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using $resource.query, I want to return an object that contains an array of the actual resource

By default, the $resource.query() is set up to expect an array of objects that become $resource objects. To accommodate paging in a nice, restful way, I have my GET /api/widgets endpoint set up to return the following object:

{
  currentPage: 1,
  perPage: 20,
  totalItems: 10039,
  items: [{...}, {...}, {...}]
}

Is there a way to make it so that angular will know that the items property is the array of items to be $resource objects?

like image 762
w.brian Avatar asked Jan 26 '15 18:01

w.brian


2 Answers

You need to specify your own custom action.

I imagine your code looks something like this:

factory('Widget', function($resource) {
  return $resource('/api/widgets');
});

Change it to this:

factory('Widget', function($resource) {
  return $resource(/api/widgets, null, {
    query: {
      method: 'GET',
      isArray: true,
      transformResponse: function(data) {
        return angular.fromJson(data).items;
      }
    }
  });
});
like image 56
Remco Haszing Avatar answered Nov 23 '22 06:11

Remco Haszing


the easy was is to use $resouce.get, if you wan to use query you can override that behaivor.

$resource('/notes/:id', null,
{
    'query':  {method:'GET', isArray:false}
});

more info https://docs.angularjs.org/api/ngResource/service/$resource

like image 23
bto.rdz Avatar answered Nov 23 '22 08:11

bto.rdz