Angular Js $http Provider Interceptors

The $http Service in Angular JS allow us to communicate smoothly with back-end services. I came into a scenario where I need to monitor all http requests/responses happening using $http service. we can do that with each $http use, but I strongly believe in not copy/past and duplicate the code over and over. so I was looking into an approach to that allow me to write a function or method that will be called with each http request made.

Angular Js supporting interceptors concept for $httpProviders service. The interceptor is a service function that will be called with each call for service..In our scenario,  you can think of the interceptor as a man monitor the traffic going back and forth.

Below code is basically adding a value to http request header and test the response status if it is 600 (custom value) then do certain action.

// interceptor logic.
app.factory('httpInterceptor', function ($q) {
    return {
        request: function(config) {
            config.headers['X-MyHeaderKey'] = "MyHeaderValue";
            return config;
        },
        requestError: function(rejectReason) {    
            //Do certain actions   
            return $q.reject(rejectReason);
        },
        response: function (response) {
             //Do certain actions
             return response;
         },
        responseError: function (response) {
            if (response.status === 600) {
                //Do needed logic in case of status 600
                return $q.reject(response);
            }
             else {
                return $q.reject(response);
            }
        }
    };
});
app.config(function ($httpProvider) {
    $httpProvider.interceptors.push('httpInterceptor');
});

$httpProviders provides 4 main types of interceptors that you can use:

1) Request Interceptor: This service method will be called when $http service send request to back-end server. in the example able we simply injected a new key/value in the http request header.

2) Response Interceptor: This service method will be called after request sent to the server and once the $http service received the response. the response will be received as a parameter to the service method.

3) RequestError Interceptor: In some cases the request can’t be sent or other interceptors reject sending the request to back-end service. In this case, this service method will be called.

4) ResponseError Interceptor: This service method will be called whenever the back-end service has failure and return error to $http service.




1 Comment on “Angular Js $http Provider Interceptors

Comments are closed.