New Toronto Group
 - New Toronto Group

An Introduction to AngularJS Interceptors

| Posted on September 21th, 2015 by Doug Riches


From time to time when making $http requests in Angular, we find the need to pre and post process each request/response. Luckily AngularJS’s $httpProvider has an array property called interceptors that contains a series of factories give us control over what is coming and going. Interceptor objects are simply Angular factories that have a defined set of methods that allow us to hook into every request and response sent via $http.

Creating an interceptor factory:

   
angular.module('ntgApp')
  .factory('simpleInterceptor', [function () {
    return {
      request: function(config){
        … //manipulate the request
        return config;
      },
      response: function(response){
        … //manipulate the response
        return response;
      }
      //you can also manipulate request and response errors with these properties:
      // requestError: , responseError:
    }
}]);
 

Registering the interceptor:

angular.module('ntgApp')
  .config(['$httpProvider', function($httpProvider) { 
    $httpProvider.interceptors.push('simpleInterceptor');
}]);
 

Using Interceptors requires a strong understanding of the $q and deferred/promise API: https://docs.angularjs.org/api/ng/service/$q

We have found interceptors to be very useful especially when implementing applications that use authentication with a web service.

Some examples of useful scenarios for Interceptors:

  • Sending a session token header automatically with every request
  • Handling 401 (unauthorized) errors and cleaning up the app’s service data when a token has expired or is invalid
  • Adding a spinner overlay during operations that render the app unusable (eg. Login)
  • Manipulating a server response into a different data format
  • Retrying a request if you receive a 503 error from a busy remote service, or a service that might be down

 

Posted in AngularJS  | Comments (0)

Comments (0)


Add a Comment





To use reCAPTCHA you must get an API key from http://recaptcha.net/api/getkey

Allowed tags: <b><i><br>Add a new comment: