Injecting different providers while loading components using ComponentResolver in Angular 2

梦想与她 提交于 2019-11-30 16:37:28

ViewContainerRef.createComponent

createComponent(componentFactory: ComponentFactory<C>, index?: number, injector?: Injector, projectableNodes?: any[][]) : ComponentRef<C>

has an injector parameter. If you pass one this one is used to resolve providers. I don't think you can override providers added to the @Component() decorator though.

You can create a new injector Injector

let injector = ReflectiveInjector.resolveAndCreate([Car, Engine])

and pass this injector or you can inject the injector to the component that calls ViewContainerRef.createComponent and create a child injector.

constructor(private injector:Injector) {}

Injector is the generic base class ReflectiveInjector is a concrete implementation.

let resolvedProviders = ReflectiveInjector.resolve([Car, Engine]);
let child = ReflectiveInjector.fromResolvedProviders(resolvedProviders, this.injector);

This way the providers that are available to the current component are passed along and Car, and Child are added. Therefore providers that child can't resolve (others than Car and Engine) are tried to resolve from the parent injector.

Plunker example

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!