Why a service of main module available in other modules?

1.6k Views Asked by At

I have a main module main which contains a service mainService. I have then injected another module moduleA in my main module. I randomly called mainService in moduleA without injecting main module and was amazed to see it is working fine.

angular.module('main', ['moduleA']);
angular.module('main').service('mainService', function(){
   //insert code here
});

angular.module('moduleA', []);
angular.module('moduleA').controller('abc', function(mainService){
   //mainService available here, without injecting main module
});

I want to know the reason behind this. I once read in a comment that a service defined in a module is available everywhere in the application, but couldn't find the source. Is it ok to continue using it like this?

I'm using AngularJS ver 1.3.15 if it helps.

3

There are 3 best solutions below

5
On BEST ANSWER

Yes you can use the service of main because of parent child relationship. "main" is a parent module and "moduleA" its child/dependency module.

Any serivce, controller, directive defined in "main" module will be available with "moduleA"

Lets understand this concept with a more complex scenario

angular.module('main', ['moduleA', 'moduleB']);


angular.module('moduleA', []);
angular.module('moduleA').service('moduleAService', function(){
   //insert code here
});

angular.module('moduleB', []);
angular.module('moduleB').controller('abc', function(moduleAService){
   //moduleAService available here, without injecting moduleA module
});

Now in this case moduleA and moduleB are totally independent but still moduleB can access moduleA services

It is because main module is dependent on moduleA and moduleB. So moduleA services is injected in main module and moduleB being a child of "main" module can access it.

0
On

Injecting something like a service in the parent, makes it available to all its children.

3
On

Worth reading http://michalostruszka.pl/blog/2015/05/21/angular-dependencies-naming-clash/ to know few more things about modules.

Summary from the post:

It turns out AngularJS doesn’t really care where it takes things to inject from as long as the name matches

In AngularJS there is no such thing as module you depend on. Even when you ask for a thing, you cannot be sure you’ll get the one you expect just because you declare dependency on module that has exactly this thing. This is all one giant toolbox.