问题描述
一个与框架无关的方式来表述这个问题是如何在服务定位器中注册另一个服务?"
A framework-agnostic way of phrasing this question is "How to register another service with the service locator?"
将Injector设置为不可变的,包括接口和实现.
The Injector is set up to be immutable, both the interface and the implementation.
interface Injector {
abstract get(token: any, notFoundValue?: any): any;
}
界面 https://github. com/angular/angular/blob/master/packages/core/src/di/injector.ts 实施 https://github.com/angular/angular/blob/master/packages/core/src/di/reflective_injector.ts
如何添加其他提供程序(动态地,而不是通过模块)?
How do you add another provider (dynamically, not via a module)?
在自举后(例如通过路由器)加载新模块时,Angular本身如何做?
How does Angular do this itself when it is loading new modules after bootstrapping, for example via the router?
推荐答案
要将提供程序添加到现有的注入器,您必须通过创建新的注入器并传递父注入器来对其进行扩展:
In order to add a provider to the existing injector you have to extend it by creating a new injector and pass the parent injector:
class Comp {
constructor(existing: Injector) {
const newInjector = ReflectiveInjector.resolveAndCreate(providers, existing)
}
}
要获取更多详细信息,请阅读反射型注入器与角度注入器之间的区别.
To get more details read Difference between Reflective Injector and Injector in Angular.
它使用了一些不同的机制.创建新的模块实例后,它会通过父注入器:
It uses a bit different mechanism. When a new module instance is created it's passed the parent injector:
class NgModuleRef_ implements NgModuleData, InternalNgModuleRef<any> {
constructor(..., public _parent: Injector) {
initNgModule(this);
}
然后,当您请求令牌时,如果在现有注入器上找不到依赖项,它将使用该父注入器来解决依赖关系:
And then when you request a token it uses this parent injector to resolve dependency if it's not found on the existing injector:
NgModuleRef_.get(token, notFoundValue = Injector.THROW_IF_NOT_FOUND) {
return resolveNgModuleDep(...);
}
export function resolveNgModuleDep(...) {
...
if (found) return instance;
return data._parent.get(depDef.token, notFoundValue); <----------------
}
这篇关于如何将另一个提供程序添加到注射器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!