Interceptor in Angular

Interceptor in Angular

$http service

This service is an Angular method for making HTTP request for external resources. All HTTP requests has an asynchronous nature. Because of that, all operations return promises. Generally, this service could be used by defining parameters directly, like below

$http({
  method: 'GET',
  url: '/someUrl'
}).then(function successCallback(response) {
    // this callback will be called asynchronously
    // when the response is available
  }, function errorCallback(response) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });

or by using shortcut methods

$http.get('/someUrl', config).then(successCallback, errorCallback);

Interceptor in Angular

The same as in previous post about interceptor in Angular you can also setup global mechanism to intercept each HTTP request. It can be useful for error handling, logging or authentication. You can use 4 types of additional configurations:

  • before sending request (request function)
  • after response retrieve (response function)
  • on error during sending request (requestError function)
  • on error during retrieving response (responseError function)

Implementation

To setup interceptor, you should only define service factory with declaring at least one of function mentioned in list above. Below you can see an example from the Angular documentation

// register the interceptor as a service 
$provide.factory('myHttpInterceptor', function($q) 
{ 
    return { 
        'request': function(config) { 
            // do something on success 
            return config || $q.when(config);
        }, 
        'requestError': function(rejection) { 
            // do something on error 
            if (canRecover(rejection)) { 
                return responseOrNewPromise 
            } 
            return $q.reject(rejection); 
        }, 
        'response': function(response) { 
            // do something on success 
            return response || $q.when(response); 
        }, 
        'responseError': function(rejection) { 
            // do something on error 
            if (canRecover(rejection)) { 
                return responseOrNewPromise 
            } 
            return $q.reject(rejection); 
        } 
    }; 
}); 
$httpProvider.interceptors.push('myHttpInterceptor');

Into this handlers you can also use asynchronous operations, because you can return promises from them.

As can be seen, it is very simple, but powerful functionality to add common behaviours to your data operations.

References:

https://docs.angularjs.org/api/ng/service/$http

http://www.webdeveasy.com/interceptors-in-angularjs-and-useful-examples/

http://www.bennadel.com/blog/2777-monitoring-http-activity-with-http-interceptors-in-angularjs.htm

http://thecodebarbarian.com/2015/01/24/angularjs-interceptors