Mark Hill
Mark Hill

Reputation: 1839

Does order of service declaration matter when creating them in a module?

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?

Upvotes: 2

Views: 971

Answers (2)

Marcus Höglund
Marcus Höglund

Reputation: 16811

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.

Upvotes: 2

crowhill
crowhill

Reputation: 2548

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?

Upvotes: 1

Related Questions