如何在Angular.js中获取拦截器对我自己定义的服务的响应?

How can I get the response of an interceptor on my own defined service in Angular.js?

我有一个带有服务 (EqService) 的 Angular 应用程序,我想知道异步调用中的 时间戳标记

我正在使用请求和响应拦截器。关键组件如下:

// app.js

var appModule = angular.module('myApp', []);

appModule.config(['$httpProvider', function($httpProvider) {
    $httpProvider.interceptors.push('timestampMarker');
}]);

appModule.controller('PostsAjaxController', function ($scope, EqService) {

    $scope.getData = function (){
        EqService.get().then(function (resp) {
            console.log(resp);
            // Want here 'config.responseTimestamp' and 'config.requestTimestamp';
        });
    };

    $scope.getData();
});

// interceptor.js

appModule.factory('timestampMarker', [function() {
    var timestampMarker = {
        request: function(config) {
            config.requestTimestamp = new Date().getTime();
            return config;
        },
        response: function(response) {
            response.config.responseTimestamp = new Date().getTime();
            return response;
        }
    };
    return timestampMarker;
}]);

// services.js

appModule.factory('EqService', function ($http, $q) {
    return {
        get: function () {
            var deferred = $q.defer();
            $http({ method: 'POST', url: './data.php'}).success(function (data) {
                deferred.resolve(data);
            });
            return deferred.promise;
        }
    }
});

我的问题是:如何在 EqService get 调用 之后得到 'config.responseTimestamp' 和 'config.requestTimestamp'

使用响应对象中的配置 属性。它包含用于发出请求的配置。 检查 https://docs.angularjs.org/api/ng/service/$http.

您应该使用 then 而不是 success 以获得一致的承诺。查看 success 实施

promise.success = function(fn) {
    // ...
    promise.then(function(response) {
        fn(response.data, response.status, response.headers, config);
    });
    return promise;
};

我们看到响应被分解了。要使用 then,您的 services.js 将如下所示:

appModule.factory('EqService', function ($http, $q) {
    return {
        get: function () {
            var deferred = $q.defer();
            $http({ method: 'POST', url: './data.php'}).then(function (response) {
                deferred.resolve(response);
            });
            return deferred.promise;
        }
    }
});