【问题标题】:AngularJS intercept all $http requestsAngularJS 拦截所有 $http 请求
【发布时间】:2013-12-17 19:33:02
【问题描述】:

我似乎无法让 $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>

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    如果您希望在拦截时选择接受/拒绝请求,您应该使用 $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); }
        };
    });
    

    我学到了一些有用的东西,谢谢

    【讨论】:

      【解决方案2】:

      返回数据后请求拦截器未运行​​。它之前运行。您的 logIt 函数在顶部插入最新消息。如果您更改代码以使用 $log 服务,您将看到拦截器首先运行。

      【讨论】:

      • 哇...现在感觉很笨。不过谢谢!在我的其他代码中发现我正在使用已弃用的 $httpProvider.responseInterceptors 而不是 $httpProvider.interceptors。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-09
      • 2012-08-11
      • 2020-05-04
      • 1970-01-01
      • 2017-02-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多