本文介绍了在Angular 2中使用ComponentResolver加载组件时注入不同的提供程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以在动态加载组件时注入不同的提供程序吗?

Can we inject different provider while loading components dynamically?

我的组件

  @Component({
     moduleId: module.id,
     selector: "my-component",
     template: "<div>my-component</div>",
     providers: [MyComponentService]
  })
  export class MyComponent{

     constructor(private ds: MyComponentService) {
        super();
     }    
   }

在其他地方

     this._cr.resolveComponent(MyComponent).then(cmpFactory => {
        let instance: any = this.testComponentContainer.createComponent(cmpFactory).instance;
    });

因此在上面的代码中,在解析MyComponent时,也会解析此MyComponentService的提供程序,我们是否可以基于某些开关来以不同的方式解决它?

so in above code, while resolving MyComponent, provider for this MyComponentService will also be resolved, can we resolve it differently based upon some switch?

推荐答案

ViewContainerRef.createComponent

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

具有一个injector参数.如果您通过一项,则此一项将用于解析提供程序.我认为您无法覆盖添加到@Component()装饰器中的提供程序.

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])

并传递此注入器,或者您可以将注入器注入调用ViewContainerRef.createComponent的组件并创建子注入器.

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是通用基类,ReflectiveInjector是具体实现.

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

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

这样,将传递当前组件可用的提供程序,并添加CarChild.因此,child无法解析的提供者(CarEngine除外)将尝试从父注入器解析.

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.

柱塞示例

这篇关于在Angular 2中使用ComponentResolver加载组件时注入不同的提供程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 02:58