Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute:

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.

share|improve this question
1  
you can't selectively apply an interceptor, so the interceptor will have to evaluate the config object (docs.angularjs.org/api/ng/service/$http#usage) of the request and decide if it should take action or not. – Claies Oct 13 at 16:49

1 Answer 1

up vote 1 down vote accepted

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
                     }
                }            

});
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.