Angular $ resource receiving metadata after conversion

I have the following API:

{ "meta": { "total_item": 1, "number_of_pages": 1, "page_number": 1, "status": "Success" }, "data": [ { "name": "Operator 1", "short_name": "OP1", "_id": "534d69bba758b3b7839ba7b9", "__v": 0, "users": [ "532ef6e28b42970ab797444f" ] } ] } 

I am using an Angular $ resource to request an API using the following code:

 var apiDataTransformer = function ($http) { return $http.defaults.transformResponse.concat([ function (data, headersGetter) { var result = data.data; result.meta = data.meta; console.log(result); return result; } ]) }; angular.module('ua.common').factory('uaApi', function($resource, $http){ var factory = {}; factory.operator_ressource = $resource( '/operators/:operatorId', {}, {'query': {method: 'GET', isArray: true, transformResponse: apiDataTransformer($http) } } ); return factory; }) 

If I print in the console, the result of a request to these resources is what I got:

 uaApi.operator_ressource.query({}, function(response){ factory.operators_list = response; console.log(response); }); // Console Output [f, $promise: Object, $resolved: true] 0: f __v: 0 _id: "534d69bba758b3b7839ba7b9" name: "Operator1" short_name: "OP1" users: Array[1] 0: "532ef6e28b42970ab797444f" 

Thus, using $ resource, even if I used transformResponse to store my data, I lost my meta object, and this is annoying, since I would like to be able, when page_number <number_of_pages, to automatically get other objects.

How can I achieve this with angular? (I think this is a common question for an Angular application using paginate api).

+6
source share
1 answer

You can return an object, including sidebar paging data, and an array of resource objects from the request method, creating them in transformResponse.

Something along the lines of:

 angular.module('ua.common').factory('uaApi', function($resource, $http){ var factory = {}; factory.operator_ressource = $resource('/operators/:operatorId', {}, {'query': { method: 'GET', isArray: false, transformResponse: function(jsondata){ return { meta : jsondata.meta, results : jsondata.map(function(result){ return new factory.operator_ressource(result); }) } } } } ); return factory; }); 

This approach works well for me; I usually create an instance of the pager object and return an array of $ resource objects to it.

+2
source

All Articles