AngularChef
AngularChef

Reputation: 14087

How to alter the data returned by $resource in Angular.js?

I'm using an API that returns JSON data in this format:

{
    paging: {
        previous: null,
        next: null
},
    data: [
        { title: 'First Item' },
        { title: 'Second Item' },
        ...
    ]
}

I'm using Angular's $resource service to fetch this data.
My code - which is located in a controller - goes something like this:

var Entity = $resource('/api/entities');
var entities = $scope.entities = Entity.get();

And then, in the view, I can display the data like this:

<ul>
  <li ng-repeat="entity in entities.data">{{entity.title}}</<li>
</ul>

It all works fine, but:

Following these indications by Dan Boyon, I managed to customize the default $resource service and to override the .get() or .query() methods, but I'm not sure where to go from there.

Upvotes: 18

Views: 16649

Answers (2)

Ismail RBOUH
Ismail RBOUH

Reputation: 10450

You can use the Response Transformer (transformResponse) like this:

$resource('/api/entities', {}, {
        query: {
            method: 'GET',
            responseType: 'json',
            isArray: true,
            transformResponse: function (response) {
                return response.data;
            }
        }
    });

This code modifies the "query" method behaviour, you can do the same for "get" ... !

Upvotes: 1

Chris
Chris

Reputation: 3915

I don't think you need to modify the get or query defaults. Just use the success callback to do what you want. It should be more robust as well.

Entity.get(
    {}, //params
    function (data) {   //success
        $scope.entities = data.data;
    },
    function (data) {   //failure
        //error handling goes here
    });

Html will be cleaner, too:

 <ul>
      <li ng-repeat="entity in entities">{{entity.title}}</<li>
 </ul>

By the way, I usually declare services for my resources and then inject them into my controllers as I need them.

 myServices.factory('Entity', ['$resource', function ($resource) {
     return $resource('/api/entities', {}, {
     });
 }]);

Upvotes: 24

Related Questions