AngularJS $http response header
Asked Answered
N

3

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));
        });

    };
Nitrile answered 27/2, 2014 at 9:31 Comment(7)
What's the output of console.log(headers()); ?Phonologist
Please see #17038936Juanajuanita
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]i58.tinypic.com/5lrzft.png[/IMG]Nitrile
And my web-config in Rest service:<httpProtocol> <customHeaders> <add name ="Access-Control-Expose-Headers" value="X-TotalPages"/> <add name="Access-Control-Allow-Origin" value="" /> <add name="Access-Control-Allow-Methods" value="POST,GET,DELETE,PATCH,PUT,OPTIONS" /> <add name="Access-Control-Allow-Headers" value="" /> </customHeaders> </httpProtocol>Nitrile
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 objectNitrile
Shouldn't it be headers('X-TotalPages')?Dunne
There you are!!! Thank you! Such a simple beautiful answer. Lack of basic knowledge from my side was the problem.Nitrile
A
38

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

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

Arvad answered 20/6, 2014 at 11:28 Comment(0)
T
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.

Tweed answered 6/2, 2020 at 11:26 Comment(0)
S
0

You can use success callback of promise

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

     });
Suet answered 5/9, 2017 at 21:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.