Reputation: 14283
For the first time ever I am facing this issue and I am struggling a lot in trying to figure out why and how to fix it.
I have two services, service1 and service 2, but apparently, there's a circular dependency like this:
serv1 <- serv2 <- serv1
The services code is the following:
angular.module('service1', [])
.service 'serv1', ['$rootScope','$http','$location','serv2',
function ($rootScope, $http, $location, serv2){
serv2.doMyOtherThing(...)
}
]
and service2 is the following:
angular.module('service2', [])
.service 'serv2', ['$rootScope','$http','$location','serv1',
function ($rootScope, $http, $location, serv1){
serv1.doMyThing(...)
}
]
why is there a circular dependency? how do I solve this?
Each service is specific for something (serv1 variou utilities and serv2 array utilities) and I need to use the two together sometimes but it's currently not possible.
Thanks for any help
Upvotes: 1
Views: 115
Reputation: 522
If you see this Miško Hevery's blog you will understand that :
...
.service 'serv1', ['$rootScope','$http','$location','serv2'
.service 'serv2', ['$rootScope','$http','$location','serv1',
The serv1 needs serv2 and serv2 needs serv1. And this is going to train a circular dependency.
So you could use a third service
Or you can resolve this like this :
angular.module('service1', [])
.service 'serv1', ['$rootScope','$http','$location','serv2',
function ($rootScope, $http, $location, serv2){
serv2.doMyOtherThing(...)
}
]
angular.module('service2', [])
.service 'serv2', ['$rootScope','$http','$location','$injector',
function ($rootScope, $http, $location, $injector){
var serv1 = $injector.get('serv1');
serv1.doMyThing(...)
}
]
Upvotes: 1
Reputation: 467
Use a third service, use that third service in the other ones.
example:
angular.module('service1',[])
.service 'serv1' [..,'servCommon', function(..,servCommon){}]
angular.module('service2',[])
.service 'serv2' [..,'servCommon', function(..,servCommon){}]
angular.module('serviceCommon',[])
.service 'servCommon' [.., function(..){}]
Add some common function in that servCommon
and use them from other two.
Hope this helps.
Upvotes: 1