简体   繁体   中英

AngularJS http interceptor with selective url

How to have an $http interceptor to react only to given patterns?

For instance, i would like the interceptor to handle every "/api/*" request and leave the other requests alone.

You can filter the url in success or rejection functions both in the request or response.

Lets say you need to handle the errors for requests and responses for urls which start with "math/".

Here is your interceptor.

$httpProvider.interceptors.push(function($q, mathError) {
                        return {

                            requestError: function(rejection){                            
                                mathError.anyError(rejection);    
                                return $q.reject(rejection);
                            },

                            responseError: function(rejection){                            
                                mathError.anyError(rejection);
                                return $q.reject(rejection);
                            }
                        };
    });

Here is your factory where you handle it

myApp.factory('mathError', function(){
    return {
                anyError: function(rejection){ 

                     if (rejection.config.url.substr(0, 5) === "math/") {

                         console.log("Only Math errors are handled here"); 

                         //Do whatever you need here
                     }
                }            

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM