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
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);
}]);
$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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With