在Angular 2中使用ComponentResolver加载组件时注入不同的提供程序
我们可以在动态加载组件时注入不同的提供者吗 我的组件在Angular 2中使用ComponentResolver加载组件时注入不同的提供程序,angular,angular2-injection,Angular,Angular2 Injection,我们可以在动态加载组件时注入不同的提供者吗 我的组件 @Component({ moduleId: module.id, selector: "my-component", template: "<div>my-component</div>", providers: [MyComponentService] }) export class MyComponent{ constructor(private d
@Component({
moduleId: module.id,
selector: "my-component",
template: "<div>my-component</div>",
providers: [MyComponentService]
})
export class MyComponent{
constructor(private ds: MyComponentService) {
super();
}
}
因此,在上面的代码中,在解析MyComponent
时,此MyComponentService
的提供程序也将被解析,我们是否可以根据某些切换以不同方式解析它?
并传递该注入器,或者您可以将注入器注入调用ViewContainerRef.createComponent
的组件,并创建子注入器
constructor(private injector:Injector) {}
Injector
是一种通用基类reflectionvenjactor
是一种具体实现
let resolvedProviders = ReflectiveInjector.resolve([Car, Engine]);
let child = ReflectiveInjector.fromResolvedProviders(resolvedProviders, this.injector);
这样,将传递当前组件可用的提供程序,并添加Car
和Child
。因此,child
无法解析的提供程序(除Car
和Engine
之外)将尝试从父喷油器解析
constructor(private injector:Injector) {}
那么,如果我不添加提供程序参数,并使用injector,那么组件工厂在动态加载组件时将注入MyComponentService,这是好的假设吗?我原以为在没有通过(未测试)的情况下会传递父注入器。如果这不起作用,那么只需将其注入当前组件并将其转发到
createComponent(…)
,或者如果您希望添加其他提供程序,则创建子注入器。当我尝试使用此.testComponentContainer.createComponent(cmpFactory,,injector)时。有什么建议吗?您添加的Plunker不起作用,我看到一些控制台错误。很抱歉。这辆破车有两处损坏。一个是我造成的。另一个似乎是由角度更新引起的。我更新了Plunker。
constructor(private injector:Injector) {}
let resolvedProviders = ReflectiveInjector.resolve([Car, Engine]);
let child = ReflectiveInjector.fromResolvedProviders(resolvedProviders, this.injector);