[英]How to use factories during the config phase (angular)
In my project I have a couple of provider
s which I initialise during startup 在我的项目中,我有几个
provider
,我在启动时进行了初始化
angular.module('myApp', [])
.config((barFooProvider, ....) => {
barFooProvider.setAPIPath = '/a/b/c';
...
});
As you can see I define an api-path here which is a string. 如您所见,我在这里定义了一个api路径,它是一个字符串。 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 ?
还是定义服务名称并随后使用$ injector的唯一方法?
You could use the $inject
property annotation ( docs ) on the $get
method of your provider: 您可以在提供程序的
$get
方法上使用$inject
属性注释( docs ):
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. 这样,所需的工厂将在服务实例化时注入到提供者的
$get
方法中。
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');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.