18

我似乎无法让 $httpProvider.interceptors 实际拦截。我在 JSFiddle 上创建了一个示例,用于记录拦截器何时运行以及 $http 响应成功的时间。请求拦截器在响应成功返回后运行。这似乎有点倒退。

我不能使用 transformRequest 因为我需要更改配置中的参数。该部分未在示例中显示。

我正在使用 AngularJS 1.1.5

http://jsfiddle.net/skeemer/K7DCN/1/

Javascript

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

myApp.factory('httpInterceptor', function ($q) {
    return {
        request: function (config) {
            logIt('- Modify request');
            return config || $q.when(config);
        }
    };
});

myApp.config(function ($httpProvider) {
    $httpProvider.interceptors.push('httpInterceptor');
});

function MyCtrl($scope, $http) {
    // Hit a server that allows cross domain XHR
    $http.get('http://server.cors-api.appspot.com/server?id=8057313&enable=true&status=200&credentials=false')
    .success(function (data) {
        //logIt(data[0].request.url);
        logIt('- GET Successful');
    });

    $scope.name = 'Superhero';
}


// Just the logging
var logs = document.getElementById('logs');

function logIt(msg) {
    var e = document.createElement('div');
    e.innerHTML = msg;
    logs.insertBefore(e, logs.firstChild);
}

HTML

<div ng-controller="MyCtrl">Hello, {{name}}!</div>
<br/>
<div id="logs"></div>
4

2 回答 2

19

如果您希望在拦截时接受/拒绝请求的选项,您应该使用 $httpProvider.responseInterceptors,请参见下面的示例:

$httpProvider.responseInterceptors.push(function($q) {
    return function(promise){
        var deferred = $q.defer();
        promise.then(
            function(response){ deferred.reject("I suddenly decided I didn't like that response"); },
            function(error){ deferred.reject(error); }
        );
        return deferred.promise;
    };
});

编辑没有阅读您的评论,实际上 responseInterceptors 现在已经过时了,这就是您的做法:

$httpProvider.interceptors.push(function($q) {
    return {
        request: function(config){ return config; },
        response: function(response) { return $q.reject(response); }
    };
});

学到了有用的东西,谢谢

于 2013-12-17T11:17:27.173 回答
9

The request interceptor isn't running after the data is returned. It's running before. Your logIt function inserts the newest message at the top. If you change your code to use the $log service, you'll see that the interceptor runs first.

于 2013-06-08T02:17:00.007 回答