javascript angularjs 为不同文件中的同一模块定义服务

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23378175/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 00:47:15  来源:igfitidea点击:

angularjs defining services for the same module in different files

javascriptangularjsservicedependency-injectionfactory

提问by Jeff Storey

I have two files in which I define services in my angular app, but when I try to use them both in my directive, I get an error saying the service provider is not found for whichever directive I define second. It seems like one service is overwriting the other. If I change the module definition in service2.js to myapp.services2, then it works. I would think I could add multiple factories to the same module this way. Can someone point out what I'm doing incorrectly?

我有两个文件,我在我的 angular 应用程序中定义了服务,但是当我尝试在我的指令中同时使用它们时,我收到一条错误消息,说找不到我定义的第二个指令的服务提供者。似乎一项服务正在覆盖另一项服务。如果我将 service2.js 中的模块定义更改为 myapp.services2,则它可以工作。我想我可以通过这种方式将多个工厂添加到同一个模块中。有人可以指出我做错了什么吗?

service1.js:

服务1.js:

var services = angular.module('myapp.services',[]);
services.factory('Service1', function() {
    // service code
});

service2.js:

service2.js:

var services = angular.module('myapp.services',[]);
services.factory('Service2', function() {
    // service code
});

mydirective.js:

我的指令.js:

angular.module('myappdirective', []).directive('myapp', ['Service1', 'Service2',
function(service1,service2) {
    // directive code
}]);

回答by aet

This is from the docs:

这是来自文档:

Beware that using angular.module('myModule', []) will create the module myModule and overwrite any existing module named myModule. Use angular.module('myModule') to retrieve an existing module.

请注意,使用 angular.module('myModule', []) 将创建模块 myModule 并覆盖任何名为 myModule 的现有模块。使用 angular.module('myModule') 检索现有模块。

Found here: https://docs.angularjs.org/guide/module

在这里找到:https: //docs.angularjs.org/guide/module

回答by Basav

This is possible, however will be error prone, hence not recommended

这是可能的,但是容易出错,因此不推荐

Make small modification to what you are already doing

对你已经在做的事情做一些小的修改

Just do not re-declare the module variable in other files other than service1.js or put the module definition to a file of its own and include these JS file in the order of Module.js, services.js, directive.js then it will work

只是不要在 service1.js 以外的其他文件中重新声明模块变量或将模块定义放在自己的文件中并按照 Module.js、services.js、directive.js 的顺序包含这些 JS 文件然后它将工作