angularjs - 为什么主模块的服务在其他模块中可用?

标签 angularjs dependency-injection

我有一个主模块 main其中包含服务 mainService .然后我注入(inject)了另一个模块 moduleA在我的主模块中。我随机调用mainServicemoduleA不注入(inject)main模块并惊讶地发现它工作正常。

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

我想知道这背后的原因。我曾经在评论中读到,模块中定义的服务在应用程序中随处可用,但找不到源。可以继续这样使用吗?

我正在使用 AngularJS ver 1.3.15如果有帮助。

最佳答案

是的,由于父子关系,您可以使用 main 的服务。 “main”是一个父模块,“moduleA”是它的子/依赖模块。

“main”模块中定义的任何服务、 Controller 、指令都将在“moduleA”中可用

让我们用更复杂的场景来理解这个概念

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 服务

这是因为主模块依赖于模块A和模块B。因此 moduleA 服务被注入(inject)到主模块中,而作为“主”模块的子模块的 moduleB 可以访问它。

关于angularjs - 为什么主模块的服务在其他模块中可用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30729386/

相关文章:

javascript - 从函数中获取数据

javascript - AngularJs ng-model 不适用于 jQuery 自动完成

angularjs - Typescript 1.4 中的 AppGyver 和 Angular Controller

c# - 将对象注入(inject)表单

wcf - 将 Ninject WCF 扩展与 WCF Web 服务一起使用

javascript - 使用 fetch 时拒绝 promise

AngularJS 模块和外部 Controller

c# - 如何使用 StructureMap 将不同的混凝土绑定(bind)到属性

asp.net - 在 MVC 3 中使用 DependencyResolver 进行 Controller 实例化时出错

java - @Inject 在 JAX-WS 中引发 NullPointerException