23

This simple problem is bugging me. I have a custom value in my response header from the Web Api Rest server. I can see it it Firebug as: X-TotalPages 204 I try to get it in my AngularJS controller. Code below. But I cant find any good examples how to do this. console.log(headers()['X-TotalPages']); logs 'undefined'

var assets = angular.module("Assets", ['ui.bootstrap']);
assets.controller('AssetSearchController', function ($scope, $http) {
    $scope.test = 'very';
    $scope.getItems = function () {
        $http({ method: 'GET', url: 'http://localhost:57772/api/assets', params: { search: 1, page: 0, pageSize: 10 } }
            ).success(function (data, status, headers, config) {
                $scope.currentPage = 4;                
                console.log(headers()['X-TotalPages']);

            $scope.items = data;
        }).
        error(function (data, status) {
            console.log(JSON.stringify(data));
            console.log(JSON.stringify(status));
        });

    };
marcos.borunda
  • 1,486
  • 1
  • 17
  • 34
Jens Alenius
  • 1,931
  • 2
  • 16
  • 20
  • 2
    What's the output of console.log(headers()); ? – mafis Feb 27 '14 at 09:37
  • 2
    Please see http://stackoverflow.com/questions/17038436/reading-response-headers-when-using-http-of-angularjs – BKM Feb 27 '14 at 09:44
  • 1
    Thanks for the quick reply. console.log(headers()); returns Headers: [object Object] so its there. I have already looked at the other issue and it does not help. This is my response, it seems to be returned by the rest server :[IMG]http://i58.tinypic.com/5lrzft.png[/IMG] – Jens Alenius Feb 27 '14 at 09:54
  • 2
    And my web-config in Rest service: – Jens Alenius Feb 27 '14 at 09:57
  • I think the header value is there as you can see in the image. I think its my lack of basic javascript knowledge thats the main problem. Maybe is just my syntax in retrieving the data from the headers object – Jens Alenius Feb 27 '14 at 10:02
  • 8
    Shouldn't it be headers('X-TotalPages')? – Wawy Feb 27 '14 at 10:03
  • There you are!!! Thank you! Such a simple beautiful answer. Lack of basic knowledge from my side was the problem. – Jens Alenius Feb 27 '14 at 10:09

3 Answers3

38

You should use: headers('X-TotalPages')

(Posting Wawy's answer so the question can be resolved.)

barsju
  • 4,408
  • 1
  • 19
  • 24
5

For $http(url).then() syntax which replaced $http(url).success().error() in newer versions of AngularJS, I used this:

$http(url).then(function(response){
            response.headers("X-TotalPages");
     });

Just using response.headers() will give all headers attached in response.

Eshank
  • 51
  • 1
  • 2
0

You can use success callback of promise

promise.then(function(resp){
            resp.headers().token(variablename)

     });
Dileep stanley
  • 148
  • 1
  • 6