AngularJS - 访问http标头

use*_*255 13 angularjs

我试图访问我的角度控制器中的http标头,但我得到了未定义.此外,我能够看到我的角度服务中的标题响应,这在我的控制器中没有反映出来.有人可以告诉我我错过了什么吗?请参阅以下代码:

服务:

cmApp.service('supplierService', function ($http, $q) {
    this.getSuppliers = function (orderByColumn, skipRows, takeRows) {
        var deferred = $q.defer();
        $http({
            method: 'GET',
            url: 'api/supplier',
            params: { orderBy: orderByColumn, skip: skipRows, take: takeRows },
            timeout: 30000, 
            cache: false
        }).
        success(function (data, status, headers, config) {
            // any required additional processing here            
            deferred.resolve(data, status, headers, config);            
        }).
        error(function (data, status) {
            deferred.reject(data, status, headers, config);
        });
        return deferred.promise;        
    }
Run Code Online (Sandbox Code Playgroud)

控制器:

   supplierService.getSuppliers($scope.orderby, $scope.skip, $scope.take)
        .then(function (data, status, headers, config) {
            **//getting undefined here.**
            $scope.totalRecords = parseInt(headers('X-TotalRowCount'));                
            $scope.suppliers = data;
        }, function (error) {
            // error handling here
        });
Run Code Online (Sandbox Code Playgroud)

use*_*255 18

我自己找到了解决方案.我所要做的就是创建一个数组并将所有这些值添加到同一个数组并将其返回给控制器.请参阅下面的更新代码:

服务:

cmApp.service('supplierService', function ($http, $q) {
    this.getSuppliers = function (orderByColumn, skipRows, takeRows) {
        var deferred = $q.defer();
        $http({
            method: 'GET',
            url: 'api/supplier',
            params: { orderBy: orderByColumn, skip: skipRows, take: takeRows },
            timeout: 30000, 
            cache: false
        }).
        success(function (data, status, headers, config) {
            // any required additional processing here 
            var results = [];
            results.data = data;
            results.headers = headers();
            results.status = status;
            results.config = config;

            deferred.resolve(results);            
        }).
        error(function (data, status) {
            deferred.reject(data, status, headers, config);
        });
        return deferred.promise;        
    }
Run Code Online (Sandbox Code Playgroud)

控制器:

supplierService.getSuppliers($scope.orderby, $scope.skip, $scope.take)
            .then(function (response) {                
                $scope.suppliers = response.data;
                $scope.totalRecords = parseInt(response.headers["x-totalrowcount"]);                
            }, function (error) {
                // error handling here
            });
Run Code Online (Sandbox Code Playgroud)


Jas*_*son 6

这个问题很旧,但$ http()会返回一个promise本身.您可以从您的服务中返回,无需创建新的承诺.即使在使用.success()和.error()之后也可以这样做,或者即使在使用.then()之后,它们也会继续链接.