angularjs 为不同文件中的同一模块定义服务 [英] angularjs defining services for the same module in different files

查看:26
本文介绍了angularjs 为不同文件中的同一模块定义服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

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

推荐答案

这是来自文档:

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

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.

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

这篇关于angularjs 为不同文件中的同一模块定义服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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