Sending parameters to Request Interceptors

1,746 views
Skip to first unread message

Rushikesh Remane

unread,
Nov 26, 2013, 5:42:56 AM11/26/13
to ang...@googlegroups.com
Case : 
I have a request interceptor implemented that works as a service. The functionality of its is to supply every request with authentication token. 
 myApp.factory('httpRequestInterceptor', function () {
  return {
    request: function (config) {
      config.headers['Auth-Token'] = 'SomeValue';
      return config;
    }
  };
});
 
myApp.config(function ($httpProvider) {
  $httpProvider.interceptors.push('httpRequestInterceptor');
});


Now every time I make some $http requests, it adds to the reqest header and every thing works just perfect. 

Problem : 

I am making $http calls from a controller. Now the authentication token will be passed to me from calling application which invokes this UI page. I want to have provision where I can catch the incoming parameters from the invoking application and use the passed parameter to the interceptor service. In short I want to pass a value from my controller to the 'httpRequestInterceptor'. 

Note that I don't have any control over invoking application.

Please let me know how do I achieve this.

Rushikesh Remane

unread,
Jan 12, 2014, 1:59:16 AM1/12/14
to ang...@googlegroups.com
Hi, 
Does any one have any solution for this.

Replies appreciated.

Pavel Pomerantsev

unread,
Jan 12, 2014, 4:32:45 AM1/12/14
to ang...@googlegroups.com
It seems to me that since http requests are made asynchronously, you cannot 'call' this interceptor yourself, and so you cannot pass parameters to it.
But you could use another factory for configuring the current value of the header.
Please see the code for this plunk: http://plnkr.co/edit/nxIZgpqlCStzHtxUWN9R
I know this is fragile since it doesn't guarantee a certain value at a certain point in time, but if different parts of the Angular app do not need to set different tokens, it should work fine.

Also, you can always pass a header value when calling $http (without the use of interceptors): http://docs.angularjs.org/api/ng.$http#description_setting-http-headers

Please let me know if it's helpful.

Ben Greer

unread,
Jan 12, 2014, 12:17:44 PM1/12/14
to ang...@googlegroups.com
you can your parameters in config with:

$httpProvider.defaults.headers.common['Auth-Token'] = 'SomeValue';

no need to use an interceptor. 

Then in your controller you can manually override the defaults for the individual request.
Reply all
Reply to author
Forward
0 new messages