Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why a service of main module available in other modules?

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.

like image 925
yoogeeks Avatar asked Jun 09 '15 10:06

yoogeeks


2 Answers

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.

like image 64
Nikhil Aggarwal Avatar answered Sep 28 '22 10:09

Nikhil Aggarwal


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

like image 23
Guinn Avatar answered Sep 28 '22 09:09

Guinn