Javascript 更换AngularJS中的模块或服务
我将如何使我的依赖项可交换?假设我在模块myDependency中存储了一个名为myService的服务。我希望能够用新服务替换myDependency以覆盖旧服务。我希望保留它,以便主应用程序仍将运行相同的服务对象变量 我只是创建一个相同的模块来覆盖它吗?或者我应该将模块引用到$variable并更改对新服务的引用吗 我的主要目标是能够包含一个新的模块javascript文件,并使其覆盖旧模块Javascript 更换AngularJS中的模块或服务,javascript,angularjs,Javascript,Angularjs,我将如何使我的依赖项可交换?假设我在模块myDependency中存储了一个名为myService的服务。我希望能够用新服务替换myDependency以覆盖旧服务。我希望保留它,以便主应用程序仍将运行相同的服务对象变量 我只是创建一个相同的模块来覆盖它吗?或者我应该将模块引用到$variable并更改对新服务的引用吗 我的主要目标是能够包含一个新的模块javascript文件,并使其覆盖旧模块 //Main application var app = angular.module('tswp'
//Main application
var app = angular.module('tswp',['myDependency'])
.controller('MyAPP',function(myService){
console.log(myService.run());
}
//Old dependency
angular.module('myDependency',[])
.service('myService',function(){
this.run = function(){
console.log("1")
}
})
//This is the new service I want to replace the old service with
angular.module('myDependency',[])
.service('myService',function(){
this.run = function(){
console.log("2")
}
})
注射剂的标识符是唯一的。通过在源代码中包含模块及其内容的定义,您正在配置全局模块,并且只提供$PROFECT服务 如果您使用已经使用过的名称定义了一个模块,那么您将丢弃以前的模块配置,并用新的模块配置替换它。只有当您真的想抛弃旧模块中定义的所有内容时,才可以这样做
//Main application
var app = angular.module('tswp',['myDependency'])
.controller('MyAPP',function(myService){
console.log(myService.run());
}
//Old dependency
angular.module('myDependency',[])
.service('myService',function(){
this.run = function(){
console.log("1")
}
})
//This is the new service I want to replace the old service with
angular.module('myDependency',[])
.service('myService',function(){
this.run = function(){
console.log("2")
}
})
如果在两个单独的模块中定义了两个同名的服务,则实际使用的配置将取决于构建主模块时依赖关系的顺序。无论最后包含哪种配置,都将覆盖以前的配置。这样做是为了替换单个服务实现,但要注意确保您的重新定义真正包含在最后
此外,您还可以使用.decorator on仅更改服务实现的特定细节。Wow!非常感谢。这正是我想要的答案。另外,我将如何注入模板?因此,如果我在js中包含一个模板文件,它会将html注入到现有的模板文件中。