Angular 'Error: $ injector: cdep Circular Dependency' when using factory in app.js
I am trying to use tokens to handle my user authentication. I hit the road and I'm not really sure where to go from here. I've looked around a bit and it looks like I should be using the service $injector
, but I'm not 100% sure. Can anyone please help?
I created a factory that receives a token from node:
angular.module('myApp').factory('authenticateInterceptor', function(authenticateToken){
var authenticateInterceptorFactory = {};
authenticateInterceptorFactory.request = function(config){
var token = authenticateToken.getToken();
if(token){
config.headers['x-access-token'] = token;
};
return config;
}
return authenticateInterceptorFactory;
});
Here is the code for the autenticateToken:
angular.module('myApp').factory('authenticateToken', function($http, $window){
authenticateTokenFactory = {};
authenticateTokenFactory.getToken = function(token){
return $window.localStorage.getItem('token');
};
return authenticateTokenFactory;
});
There are no errors here, the problem comes when I try to use this factory in my app.js.
angular.module('myApp', [
'dependancies goes here'
])
.config(function($httpProvider){
$httpProvider.interceptors.push('authenticateInterceptor');
});
Now this throws an error, I cannot pass my factory to the interceptors.
source to share
Most likely the circular dependency is caused by injecting the service $http
inside the authenticateToken
factory.
the conflict exists because in the angular bootstrap phase try to resolve dependencies $http
(as well as other core services) in that order.
-
$httpProvider
dependencies -
authenticateInterceptor
dependencies -
authenticateToken
(include$http
, and here we go back to 1.)
By the way, since the service is $http
not used in authenticationFactory, you can even remove the injection, but if you need this service you can try injecting it dynamically just to avoid it.
angular.module('myApp').factory('authenticateToken', function($injector, $window){
authenticateTokenFactory = {};
authenticateTokenFactory.getToken = function(token){
return $window.localStorage.getItem('token');
};
authenticateTokenFactory.otherMethod = function(){
//this code is not reached when your interceptor is added to
//$httpProvider interceptors array so theorically neither the exception
var http = $injector.get('$http');
http.get (/)...
}
return authenticateTokenFactory;
});
source to share