5

I am trying to inject custom header to every API request. When I am providing some hard coded text it works.

Working code

myApp.config(['$httpProvider', function ($httpProvider) { var requestInterceptor = ['$q', '$rootScope', function ($q, $rootScope) { var interceptorInstance = { request: function (config) { config.headers['X-MyApp-CustomHeader'] = "foobar"; return config || $q.when(config); } }; return interceptorInstance; }]; $httpProvider.interceptors.push(requestInterceptor); }]); 

Not working code

myApp.config(['$httpProvider', function ($httpProvider) { var requestInterceptor = ['$q', '$rootScope', '$route', function ($q, $rootScope, $route ) { var interceptorInstance = { request: function (config) { config.headers['X-MyApp-CustomHeader'] = $route.current.params.CustomParameter; return config || $q.when(config); } }; return interceptorInstance; }]; $httpProvider.interceptors.push(requestInterceptor); }]); 

Error, When trying to inject $route

Uncaught Error: [$injector:cdep] Circular dependency found: $route <- $http http://errors.angularjs.org/1.2.3/$injector/cdep?p0=%24route%20%3C-%20%24http

1 Answer 1

18

This is a known issue.

Check out my answer: Is there a way to request $http for an interceptor?

$route depends on $http which in turn depends on the interceptors:

myApp.config(['$httpProvider', function ($httpProvider) { var requestInterceptor = ['$q', '$rootScope', '$injector', function ( $q, $rootScope, $injector ) { var interceptorInstance = { request: function (config) { var $route = $injector.get('$route'); config.headers['X-MyApp-CustomHeader'] = $route.current.params.CustomParameter; return config || $q.when(config); } }; return interceptorInstance; }]; $httpProvider.interceptors.push(requestInterceptor); }]); 

what is $injector?

$injector is used to retrieve object instances as defined by provider , instantiate types, invoke methods, and load modules.

Internally, angular.js would use $injector to invoke your methods ( config / run blocks ) with all the dependencies injected. This happens automatically so you rarely need to worry about it. In cases where $injector fails to resolve your dependencies you can do it manually.

Sign up to request clarification or add additional context in comments.

1 Comment

This doesn't work for me. The $route doesn't contain the current route on it, it just contains the routes, a reload function and the updateParams function. Angular 1.5.7.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.