23

这个简单的问题困扰着我。我在来自 Web Api Rest 服务器的响应标头中有一个自定义值。我可以看到它 Firebug 为:X-TotalPages 204 我尝试在我的 AngularJS 控制器中获取它。代码如下。但我找不到任何好的例子来做到这一点。console.log(headers()['X-TotalPages']); 记录“未定义”

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

    };
4

3 回答 3

37

你应该使用:headers('X-TotalPages')

(发布 Wawy 的答案,以便可以解决问题。)

于 2014-06-20T11:28:30.423 回答
4

对于在较新版本的 AngularJS中替换 $http(url).success().error()的 $http(url).then( )语法,我使用了这个:

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

只需使用response.headers()将给出所有附加的标题作为响应。

于 2020-02-06T11:26:08.753 回答
0

你可以使用 promise 的成功回调

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

     });
于 2017-09-05T21:33:22.767 回答