Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular $resource accessing meta data after transformRespone

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 Angular $resource to query the 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 query to those resources here 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"

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

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

like image 546
Alex Grs Avatar asked Apr 18 '14 07:04

Alex Grs


1 Answers

You can return an object including your sideband paging data and an array of resource objects from the query method, instantiating 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 instantiate a pager object and return an array of $resource objects with it.

like image 195
rych Avatar answered Nov 08 '22 21:11

rych