Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • I'd rather expose only the contents of entities.data to the view, instead of the whole entities object. How can I intercept the data returned by the GET request to modify it before it populates $scope.entities?
  • Correlated question: since I am fetching an array of data, it would be cleaner to use Entity.query() instead of Entity.get(). But if I use Entity.query() in the code above, I get an error "TypeError: Object # has no method 'push'". This makes sense, since the API is returning an object instead of an array (hence, no 'push' method on the object). Again, if I could extract the .data attribute from the response, I'd have an array.

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.

like image 216
AngularChef Avatar asked Aug 08 '12 01:08

AngularChef


People also ask

What is $resource in AngularJS?

$resource documentation describes it as: A factory which creates a resource object that lets you interact with RESTful server-side data sources. $resource is most powerful when it's configured with a classic RESTful backend.

What is $q AngularJS?

$q is integrated with the $rootScope. Scope Scope model observation mechanism in AngularJS, which means faster propagation of resolution or rejection into your models and avoiding unnecessary browser repaints, which would result in flickering UI. Q has many more features than $q, but that comes at a cost of bytes.

What is a service in AngularJS?

In AngularJS, a service is a function, or object, that is available for, and limited to, your AngularJS application. AngularJS has about 30 built-in services. One of them is the $location service.

What is an angular factory?

What is Factory in AngularJS? Factory is an angular function which is used to return the values. A value on demand is created by the factory, whenever a service or controller needs it. Once the value is created, it is reused for all services and controllers. We can use the factory to create a service.


2 Answers

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', {}, {
     });
 }]);
like image 176
Chris Avatar answered Oct 17 '22 01:10

Chris


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" ... !

like image 1
Ismail RBOUH Avatar answered Oct 17 '22 02:10

Ismail RBOUH