AngularJS intercept all $http requests

前端 未结 2 1257
感情败类
感情败类 2021-01-01 17:44

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 i

相关标签:
2条回答
  • 2021-01-01 18:27

    If you want the option to accept/reject a request at interception time you should be using $httpProvider.responseInterceptors, see example below:

    $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;
        };
    });
    

    EDIT Didn't read your comment, indeed responseInterceptors is now obsolete an that's how you do it instead:

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

    I learned something useful, thanks

    0 讨论(0)
  • 2021-01-01 18:43

    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.

    0 讨论(0)
提交回复
热议问题