Skip to content

Aquent | DEV6

Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages

An Introduction to AngularJS Interceptors

Written 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:

  .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:

  .config(['$httpProvider', function($httpProvider) { 

Using Interceptors requires a strong understanding of the $q and deferred/promise API:$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

Sign up for our Angular Course

Learn the most recent version and start building your own Angular apps

view course details