Search code examples
angularjsangular-resource

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?


Solution

  • 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;
          }
        }
      });
    });