gpt4 book ai didi

angularjs - AngularJS 中的模块和 namespace /名称冲突

转载 作者:行者123 更新时间:2023-12-03 01:41:44 25 4
gpt4 key购买 nike

考虑以下 jfiddle 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 应用程序有一个注入(inject)器,它保存所有对象的名称,而不考虑模块名称。

AngularJS Developer Guide说:

To manage the responsibility of dependency creation, each Angular application has an injector. The injector is a service locator that is responsible for construction and lookup of dependencies.

正如您所提到的,将模块注入(inject)主/应用程序模块时可能会导致严重的错误。当发生冲突时,它们会保持沉默,获胜者由最后注入(inject)的模块决定。

所以不,没有内置的方法来避免这些冲突。也许这会在未来发生。对于更可能出现此问题的大型应用程序,命名约定是最好的工具,这是正确的。考虑属于模块或功能区域的对象是否可以使用短前缀。

关于angularjs - AngularJS 中的模块和 namespace /名称冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13406791/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com