考虑下面的jsfiddlehttp://jsfiddle.net/bchapman26/9uUBU/29/ http://jsfiddle.net/bchapman26/9uUBU/29/
//angular.js example for factory vs service
var app = angular.module('myApp', ['module1', 'module2']);
var service1module = angular.module('module1', []);
service1module.factory('myService', function() {
return {
sayHello: function(text) {
return "Service1 says \"Hello " + text + "\"";
},
sayGoodbye: function(text) {
return "Service1 says \"Goodbye " + text + "\"";
}
};
});
var service2module = angular.module('module2', []);
service2module.factory('myService', function() {
return {
sayHello: function(text) {
return "Service2 says \"Hello " + text + "\"";
},
sayGoodbye: function(text) {
return "Service2 says \"Goodbye " + text + "\"";
}
};
});
function HelloCtrl($scope, myService) {
$scope.fromService1 = myService.sayHello("World");
}
function GoodbyeCtrl($scope, myService) {
$scope.fromService2 = myService.sayGoodbye("World");
}
我有 2 个模块(模块 1 和模块 2)。 module1 和 module2 都定义了一个名为 myService 的服务。当两个模块都导入到 myApp 中时,这似乎会在 Angular 中的 myService 上产生名称冲突。 AngularJs 似乎只是使用了第二个服务定义,而没有警告您可能出现的问题。
非常大的项目(或者只是重用一般的模块)会有名称冲突的风险,这可能很难调试。
有没有办法在名称前加上模块名称前缀,这样就不会发生名称冲突?
截至目前,AngularJS 模块不提供任何类型的命名空间来防止不同模块中的对象之间发生冲突。原因是 AngularJS 应用程序有一个注入器,它保存所有对象的名称,而不考虑模块名称。
The AngularJS 开发人员指南 http://docs.angularjs.org/guide/di says:
为了管理依赖创建的责任,每个 Angular
应用程序有一个注入器。注入器是一个服务定位器
负责构建和查找依赖关系。
正如您所提到的,将模块注入主/应用程序模块时可能会导致严重的错误。当发生碰撞时,它们会保持沉默,获胜者由最后注入的模块决定。
所以不,没有内置的方法来避免这些冲突。也许这会在未来发生。对于更可能出现此问题的大型应用程序,命名约定是最好的工具,这是正确的。考虑属于模块或功能区域的对象是否可以使用短前缀。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)