AngularJS intercept all $http requests

前端 未结 2 1272
感情败类
感情败类 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

提交回复
热议问题