2

Hey everyone just a structural question regarding services in Angular JS.

I have a module:

var mod = angular.module('myapp', []);

mod.config(function(){
    // some various config stuff
});

I create three services, where some of them have an onto dependency and some have a one-to-one dependency.

mod.service('service1', ['service2', function(service2){

}]);

mod.service('service2', ['service1', function(service1){

}]);

mod.service('service3', ['service1, service2', function(service1, service2){

}]);

Since they are all being declared upon the initialization of the module myApp then would this structure be allowed?

Mark Hill
  • 1,769
  • 2
  • 18
  • 33

2 Answers2

2

If service1 depends on service2 and service2 depends on service1, then you've introduced circle dependencies and got a code smell in your application. AngularJs is build upon dependency injection and the circle dependency disables it. In some cases this is a acceptable solution but in angularjs, it's not.

One way to solve this is to ask yourself if service1 and service2 should be one single service?

Read Marks great answer on circle dependencies here for a better explaination on that point.

Community
  • 1
  • 1
Marcus Höglund
  • 16,172
  • 11
  • 47
  • 69
  • @estus ok, I thought the modules were injected one by one in the main app and that didn't work. Thanks for learning me:) – Marcus Höglund Jun 20 '16 at 19:07
  • No, it is ok even if they were different modules. The only time when order matters is the injection of service providers that belong to different modules. – Estus Flask Jun 20 '16 at 19:17
  • @estus So then the answer from crownhill below is correct then? – Mark Hill Jun 20 '16 at 19:19
  • @MarkHill Both answers are correct. The order is not a problem. But circular dependency is. You should get [$injector:cdep](https://docs.angularjs.org/error/$injector/cdep) from that. – Estus Flask Jun 20 '16 at 19:21
1

You can do that, sure. The module itself should be loaded in app.js at which point all services contained within will be available for injection wherever, including other services.

That said, I'm not 100% sure what you're looking for. Is the above not working?

crowhill
  • 2,398
  • 3
  • 26
  • 55
  • No this is the answer I'm looking for. I haven't tested the build yet, I just wanted to make sure if was an acceptable structure so I didn't waste a terribly large amount of time on something that wasn't going to work. – Mark Hill Jun 20 '16 at 19:18