What is interceptor

Angular’s HTTP interceptors can be used to pre- and postprocess HTTP requests. Preprocessing happens before requests are executed. This can be used to change request configurations. Postprocessing happens once responses have been received. Responses can be transformed via postprocessing.

Global error handling, authentication, loading animations and many more cross-cutting concerns can be implemented with HTTP interceptors.

const module = angular.module('interceptorTest', []);

module.config($httpProvider => {
  $httpProvider.interceptors.push(
    createInterceptor.bind(null, 'A'),
    createInterceptor.bind(null, 'B')
  );
});

module.run($http => {
  $http.get('https://api.github.com')
  .then(response =>; console.log('Response handler'));
});

angular.bootstrap(document.documentElement, [module.name]);

function createInterceptor(id) {
  return {
    request(config) {
      console.log(`Interceptor ${id}: Request`);
      return config;
    },

    response(response) {
      console.log(`Interceptor ${id}: Response`);
      return response;
    }
  };
}

// Generates the following output:
// Interceptor A: Request
// Interceptor B: Request
// Interceptor B: Response
// Interceptor A: Response
// Response handler

results matching ""

    No results matching ""