angular multiple interceptors in app.config

4k views Asked by At

in my angular app, I want to add informations to all calls to an external API.

To do so, I use interceptors that I call from within app.config.

app.config(['$httpProvider', ... , function($httpProvider, ...){      
    $httpProvider.interceptors.push('globalInterceptorService');
    $httpProvider.interceptors.push('authInterceptorService');
}]);

It works fine when I only use one interceptor. But when I use 2 of them (as in the example above) the action of one gets overridden by the other.

Any idea about how to deal with multiple interceptors? Maybe is it recommended to have only 1? Any help is much appreciate.

Interceptor 1 :

function globalInterceptorService ($q, localStorageService) {

  var service = {};

  var _request = function (config) {

    config.headers = config.headers || {};

    var AreaId = localStorageService.get('AreaId');
    if (AreaId) {

      config.headers.AreaId = 'AreaId ' + AreaId;

    }

    return config;
  };

  service.request = _request;

  return service;
}

Interceptor 2 :

function authInterceptorService ($q, $location, localStorageService) {

  var service = {};

  var _request = function (config) {

    config.headers = config.headers || {};

    var authData = localStorageService.get('authorizationData');
    if (authData) {
      config.headers.Authorization = 'Bearer ' + authData.token;
    }

    return config;
  };

  service.request = _request;

  return service;
}
1

There are 1 answers

3
akn On BEST ANSWER

I think you should push the function, not its string name.

function globalInterceptorService($q, localStorageService){...}
$httpProvider.interceptors.push(globalInterceptorService);

example: http://jsfiddle.net/aartek/tbhobfbu

Or

function globalInterceptorService($q, localStorageService){...}
$provide.factory('globalInterceptorService',globalInterceptorService)
$httpProvider.interceptors.push('globalInterceptorService');

example: http://jsfiddle.net/aartek/tbhobfbu/2/

It's well described in the documentation