In my project I have a couple of provider
s which I initialise during startup
angular.module('myApp', [])
.config((barFooProvider, ....) => {
barFooProvider.setAPIPath = '/a/b/c';
...
});
As you can see I define an api-path here which is a string. But how can I set for example a factory ? Or is the only way to define the name of the service and later on use the $injector ?
You could use the $inject
property annotation ( docs ) on the $get
method of your provider:
myApp.provider('test', function() {
this.setFactoryName = function(name) {
this.$get.$inject = [name];
};
this.$get = function(factory) {
return {
getMessageFromFactory: function() {
return factory.msg;
}
};
};
// set default value
this.setFactoryName('myFactory1');
});
then configure it this way:
myApp.config(function(testProvider){
testProvider.setFactoryName('myFactory2');
});
This way the required factory will be injected to the $get
method of your provider upon service instantiation.
You just can use Providers in Config Phase
In other words Providers are Configurable in AngularJs
May be this link would be helpfull
providers are the only services that can be used in config phase!
app.provider('test', function() {
// set default path
var APIPath = 'a/b/c';
function setAPIPath(path) {
APIPath = path;
}
});
angular.module('app', []).config(function(testProvider) {
// set path during config
testProvider.setAPIPath('x/v/b');
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.