2016-06-09 40 views
1

我們可以在動態加載組件時注入不同的提供者嗎?在Angular 2中使用ComponentResolver加載組件時注入不同的提供者

我組分

@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也將得到解決,我們可以不同的解決問題基於一些開關?

回答

3

ViewContainerRef.createComponent

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

具有injector參數。如果你通過一個這個被用來解析提供者。我不認爲你可以覆蓋添加到@Component()修飾器的提供者。

您可以創建一個新的注射器Injector

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

,並通過該噴射器,也可以注入注射器調用ViewContainerRef.createComponent組件,並創建子注射器。

constructor(private injector:Injector) {} 

Injector是通用基礎類ReflectiveInjector是一個具體的實現。

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

這種方式是提供給當前組件的提供商一起和Car過去了,Child加入。因此child無法解析的提供程序(CarEngine以外的其他提供程序)嘗試從父注入器解析。

Plunker example

+0

所以是很好的假設,如果我不加提供商參數,並使用注射器然後組件工廠將同時動態加載組件注入MyComponentService? –

+0

我原本以爲沒有人通過(未測試)時,父注入器會被傳遞。如果這不起作用,那麼只需將其注入當前組件並將其轉發給'createComponent(...)',或者如果您想添加其他提供程序,則創建一個子注入器。 –

+0

當我嘗試使用this.testComponentContainer.createComponent(cmpFactory,<我應該傳遞給我什麼,因爲我已經有ViewContainerRef,它要求我傳遞索引,如果我傳遞0或null拋出錯誤>,注入器)。有什麼建議麼? –

相關問題