且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

AngularJS拦截所有$ http请求

更新时间:2022-10-29 13:22:50

请求拦截器不返回数据后运行。它的运行前。您的Logit函数插入顶部的最新消息。如果您改变code使用$日志服务,你会看到拦截器首次运行。

I can't seem to get the $httpProvider.interceptors to actually intercept. I created a sample on JSFiddle that logs when the interceptor is run and when the $http response is successful. The request interceptor is run after the response is already returned as successful. This seems a bit backwards.

I can't use transformRequest because I need to alter the params in the config. That part isn't shown in the sample.

I'm using 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>

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.