Stefano Mancini
Stefano Mancini

Reputation: 221

Get Response Headers in Restangular getList

my Rails API wites pagination data in the response headers in this way:

X-Pagination {"total":332,"total_pages":12,"first_page":true,"last_page":false,"previous_page":null,"next_page":2,"out_of_bounds":false,"offset":0}

I need to access this value during a getList() call in order to display paginator and so on.

I've seen that the headers are empty.

How can I solve this issue?

Thanks, Stefano

Upvotes: 7

Views: 5654

Answers (3)

fracz
fracz

Reputation: 21278

If you want to read only particular headers of the response and you don't need full responses with header in all Restangular requests, you can look for the header in the response interceptor and add it to the response.

app.config(function(RestangularProvider) {
  RestangularProvider.addResponseInterceptor(function(data, operation, what, url, response, deferred) {
    var pagination;
    if (pagination = response.headers('X-Pagination')) {
      data.paginationData= pagination;
    }
    return data;
  });
});

Upvotes: 0

Urigo
Urigo

Reputation: 3185

To add on 2j2e's answer, i've created a factory and I use that like this:

angular.module('myApp')
  .factory('RestFullResponse', ['Restangular', function (Restangular) {
    return Restangular.withConfig(function (RestangularConfigurer) {
      RestangularConfigurer.setFullResponse(true);
    });
  }]);

And in the controller:

angular.module('myApp')
  .controller('PikachuCtrl', function ($scope, Restangular, RestFullResponse) {

    var ideas = RestFullResponse.all('Pikachus');

    ideas.getList().then(function(response){
          $scope.Pikachus = response.data;
          var XPagination = response.headers('X-Pagination');
        };
})

Upvotes: 4

user304117
user304117

Reputation:

You can use setFullResponse method it will return all response data. I suppose you need a full response as an exception so just configure Restangular locally like:

var rest = Restangular.withConfig(function(RestangularConfigurer) {
    RestangularConfigurer.setFullResponse(true);
});
rest.getList().then(function(response) {
    console.log(response.headers('X-Pagination'));
});

Upvotes: 9

Related Questions