加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

AngularJS中的模块和命名空间/名称冲突

发布时间:2020-12-17 08:54:25 所属栏目:安全 来源:网络整理
导读:考虑下面的jfiddle http://jsfiddle.net/bchapman26/9uUBU/29/ //angular.js example for factory vs servicevar app = angular.module('myApp',['module1','module2']);var service1module = angular.module('module1',[]);service1module.factory('myServi
考虑下面的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个模块(module1和module2)。 module1和module2都定义了一个名为myService的服务。这似乎在两个模块导入到myApp时在Angular中的myService上创建名称冲突。看来AngularJs只是使用第二个服务定义,而不会警告您可能的问题。

非常大的项目(或者只是重复使用模块)会有名字冲突的风险,这可能很难调试。

有没有办法用模块名称前缀名称,以便不发生名称冲突?

到今天为止,AngularJS模块不提供任何种类的命名空间,以防止不同模块中的对象之间的冲突。原因是AngularJS应用程序有一个单一的注入器,保存所有对象的名称,而不考虑模块名称。

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.

正如你所提到的,在将模块注入到你的main / app模块时,可能会导致糟糕的错误。当碰撞发生时,它们是沉默的,并且获胜者由最后注入的模块确定。

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读