为什么主模块的其他模块提供服务? [英] Why a service of main module available in other modules?

查看:95
本文介绍了为什么主模块的其他模块提供服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个主模块其中包含一个服务 mainService 。然后我注入了另一个模块 moduleA 我的主要模块中。笔者随机名为 mainService moduleA 无需进模块很惊讶地看到它工作正常。

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?

我用 AngularJS版本1.3.15 如果它帮助。

推荐答案

是的,你可以使用,因为父子关系的主要服务。 主是一个父模块和moduleA其子/依赖性模块。

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

在主模块定义的任何serivce,控制器,指令将随同moduleA

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
});

现在在这种情况下moduleA和moduleB是完全独立的,但仍moduleB可以访问moduleA服务

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

这是因为主模块依赖于moduleA和moduleB。所以moduleA服务的主模块中注入moduleB是主模块的孩子可以访问它。

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.

这篇关于为什么主模块的其他模块提供服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆