當我想在角度2(rc6)中重用相同的基本組件時,我需要在擴展基本組件的所有構造函數中使用相同的依賴聲明,否則依賴注入中斷,因爲它試圖總是注入相同的依賴聲明(我認爲這是擴展基本組件的最後一個導入的組件)。當重用相同的基本組件時角度2依賴注入
例如,我有鹼組分「動物成分」:
@Component({
selector: '#animalComponent',
template: `I'm a animal component`
})
export class AnimalComponent
{
constructor(
@Inject('AnimalData') protected _data: any
) {}
}
我延伸在兩個組件「CatComponent」基礎組分和「DogComponent」
@Component({
selector: '#catComponent',
template: `I'm a cat component`
})
export class CatComponent extends AnimalComponent
{
constructor(
@Inject('CatData') data: any
) {
super(
data
);
}
}
@Component({
selector: '#dogComponent',
template: `I'm a dog component`
})
export class DogComponent extends AnimalComponent
{
constructor(
@Inject('DogData') data: any
) {
super(
data
);
}
}
然後我包裹兩者組件在模塊中,所以我可以在運行時加載它們
@NgModule({
imports: [CommonModule],
declarations: [CatComponent],
exports: [CatComponent]
})
export class CatModule {}
@NgModule({
imports: [CommonModule],
declarations: [DogComponent],
exports: [DogComponent]
})
export class DogModule {}
最後我會加載t他在我的最後一個組件
import {DogModule} from './dog.module';
import {CatModule} from './cat.module';
@Component({
selector: '#mainComponent',
template: `
I'm a main component
<template #catComponent></template>
<template #dogComponent></template>
`
})
export class MainComponent
{
@ViewChild('catComponent', {read: ViewContainerRef}) catView: ViewContainerRef;
@ViewChild('dogComponent', {read: ViewContainerRef}) dogView: ViewContainerRef;
constructor(
protected _injector: Injector,
protected _compiler: Compiler
) {
let catInjector = ReflectiveInjector.fromResolvedProviders(
ReflectiveInjector.resolve({provide: 'CatData', useValue: 'Some cat information'}),
this._injector
);
this._compiler.compileModuleAndAllComponentsAsync(CatModule).then(
moduleFactory => {
let compFactory = moduleFactory.componentFactories.find(tmpCompFactory => tmpCompFactory.componentType.name === 'CatComponent');
let componentRef = this.catView.createComponent(compFactory, 0, catInjector, []);
}
);
let dogInjector = ReflectiveInjector.fromResolvedProviders(
ReflectiveInjector.resolve({provide: 'DogData', useValue: 'Some dog information'}),
this._injector
);
this._compiler.compileModuleAndAllComponentsAsync(DogModule).then(
moduleFactory => {
let compFactory = moduleFactory.componentFactories.find(tmpCompFactory => tmpCompFactory.componentType.name === 'DogComponent');
let componentRef = this.dogView.createComponent(compFactory, 0, dogInjector, []);
}
);
}
}
兩個組件在這種虛擬情況下,組件注入將白衣破裂時試圖解決「DogComponent」的依賴注入的消息:「不!提供商CatData」但是,如果我更改同名(「AnyAnimalData」而不是「CatData」和「DogData」)的提供者的名稱,所有工作正常。
其他人有同樣的問題?難道我做錯了什麼?