我有一个服务,我希望能够通过传入一个函数来配置它以供使用。只要这个函数返回我的服务可以使用的东西,它并不关心它如何获取数据,也不关心同步/异步。以下是我想要做的事情的示例,但由于明显的原因而无法实现:
.config(function(MyServiceProvider, OtherService) {
MyServiceProvider.setSomeMethod( OtherService.someMethod );
})
那太棒了,但似乎没有办法从配置函数中引用“OtherService”。我知道这是因为 OtherService
可能尚未配置,因此它的实例尚不应该存在,但是在这种情况下人们该怎么办?
在运行 block 中进行这种关联是否合适?(带着焦虑)吗?
.run(function(MyService, OtherService) {
MyService.setSomeMethod( OtherService.someMethod );
})
最佳答案
使用$injector当 Bootstrap 解决后,服务将在稍后解决依赖关系。
例如:
angular.module('myApp').config(function(myProvider) {
myProvider.setMethod('myUberMethod');
});
// Somewhere in myProvider
var theUberMethod, theUberMethodName;
function setMethod(dependencyName) {
theUberMethodName = dependencyName;
}
function performTheMethod() {
theUberMethod = theUberMethod || $injector.get(theUberMethodName);
// Magic
theUberMethod();
}
您甚至可能想查看 $injector 的 invoke 方法,因为它允许您将参数注入(inject)到已注入(inject)的函数方法中。
编辑
我必须更好地解释它。
您面临的问题与注入(inject)模块未在配置阶段初始化有关,因此您无法将服务注入(inject)到配置中功能。仅允许提供商。您必须将任何依赖项解析推迟到配置阶段之后。这可以通过在提供者上使用 $get 函数或注入(inject) $injector 服务并使用它来进行解析来完成。
函数可以像任何其他对象一样注册用于依赖注入(inject)。因此,向提供者提供函数的名称就足以让它在稍后解析并执行它。
myApp.provider('myFunctionCallee', function() {
var self = this;
return {
hookMyFunction: function(value /* string: name of the function */ ) {
self.myFunction = value;
},
$get: function($injector) {
return {
executeMyFunction: function() {
return $injector.get(self.myFunction)();
}
};
}
};
});
现在我们需要一种方法来通知函数的注入(inject)器。
示例一
这是最简单的...只需直接向注入(inject)器注册一个函数(对象)即可。我们将通过请求“myFunction”来解析该函数。
myApp.value('myFunction', function() {
return 'hello injected function!';
});
myApp.config(function(myFunctionCalleeProvider) {
myFunctionCalleeProvider.hookMyFunction('myFunction');
});
示例二
这个方法看起来很像前一个方法。我们将直接注册一个函数,但我们也会将其注入(inject)到我们的目标服务中。
myApp.value('myFunction', function() {
return 'hello injected service function 1';
});
myApp.factory('myService', function(myFunction) {
return {
myServiceFunction: myFunction
};
});
myApp.config(function(myFunctionCalleeProvider) {
myFunctionCalleeProvider.hookMyFunction('myFunction');
});
示例三
有时以前的方法是行不通的。也许代码是由其他人编写的,而他/她没有您所拥有的伟大愿景。但是,我们可以在任何可注入(inject)对象上公开任何函数:
myApp.factory('myService', function() {
return {
// We want to target this beast
myServiceFunction: function() {
return 'hello injected service function 2';
}
};
});
// Inject the target service here ...
myApp.factory('myFunction', function(myService) {
// ... and expose the beast.
return myService.myServiceFunction;
});
myApp.config(function(myFunctionCalleeProvider) {
myFunctionCalleeProvider.hookMyFunction('myFunction');
});
你可以在这个plunker中看到、摸到、舔到它。 .
关于javascript - 配置服务(通过其提供者)以使用另一服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22773087/