简体   繁体   English

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

[英]angularjs defining services for the same module in different files

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. 如果我将service2.js中的模块定义更改为myapp.services2,那么它可以正常工作。 I would think I could add multiple factories to the same module this way. 我想我可以通过这种方式将多个工厂添加到同一模块中。 Can someone point out what I'm doing incorrectly? 有人能指出我做错了什么吗?

service1.js: service1.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: mydirective.js:

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

This is from the docs: 这是来自文档:

Beware that using angular.module('myModule', []) will create the module myModule and overwrite any existing module named myModule. 请注意,使用angular.module('myModule',[])将创建模块myModule并覆盖任何名为myModule的现有模块。 Use angular.module('myModule') to retrieve an existing module. 使用angular.module('myModule')检索现有模块。

Found here: https://docs.angularjs.org/guide/module 在此处找到: https//docs.angularjs.org/guide/module

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文件然后它将工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM