Reputation: 21
How would I go about making my dependencies interchangable? Say I have a service called myService stored in the module myDependency. I want to be able to replace myDependency with a new service to override the old service. I want to keep it so the main application will still run the same service object variable.
Do I just create an identical module to overwrite it? Or should I reference the module to a $variable and change the reference to the new service?
My main objective is just to be able to include a new module javascript file and have it overwrite the old module.
//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")
}
})
Upvotes: 0
Views: 664
Reputation: 7214
Identifiers of injectables are unique. By including your source code with definitions of modules (and their contents) you're configuring the global (one and only) $provide
service.
If you define a module with a name that's already been used, you're throwing previous module configuration away (all of it) and replacing it with new one (see the explanation). Do this only if you really want to throw away everything that was defined in the old module.
If you define two services with the same name in two separate modules, the actual configuration used will depend on the order of dependencies when constructing your main module. Whichever configuration gets included the last will overwrite the previous configurations. Do this to replace a single service implementation, but take care to ensure that your re-definition is really included last.
Additionally, you can use .decorator()
on $provide to change only specific details of a service's implementation.
Upvotes: 0