An Introduction to AngularJS Interceptors
Sep 21 2015 02:23pm | | Share

An Introduction to AngularJS Interceptors

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
Profile picture for user driches
Doug Riches

Doug is DEV6’s Principal Consultant and leads the charge around new software development technology.  He is the go-to person for defining mobile solutions and delivering Full-Stack training.  Doug also works directly with DEV6 clients to help them define optimal user experiences. In addition to being the senior technical contact for our customers, he also plays a strong role in business development. Internally, Doug is also key person in mentoring our employees. Prior to DEV6, Doug served as Group Technical Director at Critical Mass in Toronto. While at Critical Mass, Doug provided leadership to the Technology Group and successfully built and mentored a team of highly skilled web and application developers as well as QA and Release Engineering personnel.