在 Angular 2 中使用 @Inject 时无法扩展超类



与我所读到的相反,我似乎无法扩展基类需要注入OpaqueToken引用的类。

示例:

@Component({})
export class StructureBase_Cmp {
    constructor(private constants:App_Const){
    }
}

在本例中,App_Const来自模块中提供的OpaqueToken,如下所示:

providers: [
    {provide: App_Const, useValue: Constants}
],

我知道,无论出于什么原因,你都需要调用@Inject,从而将第一个示例更改为:

@Component({})
export class StructureBase_Cmp {
    constructor(@Inject(App_Const) private constants){
    }
}

这很好用。无法正常工作的是尝试扩展该类,因为它抱怨"私有常量"在派生类中属于不同的类型:

@Component({})
export class Hero_Cmp extends StructureBase_Cmp{
    constructor(@Inject(App_Const) protected constants) {
        super(constants);
    }
}

然而,我不能将超级类更改为:

@Component({})
export class StructureBase_Cmp {
    constructor(private constants:App_Const){
    }
}

因为。。。。什么,App_Const是OpaqueToken,而不是定义的类型?尽管有医生,我还是非常困惑,因为这感觉某种味道的东西应该开箱即用。

tldr:我想扩展一个需要从OpaqueToken派生的注入项的类,但是为了做到这一点,我需要在派生类上使用@Inject,无论出于什么原因,它都会破坏父类。

感谢您的帮助。谢谢

我想说,这个问题与角度或IoC无关。这只是一个typescript编译器检查(请在此处观察(:

export class StructureBase_Cmp {
    constructor(private constants){
    }
}
export class Hero_Cmp extends StructureBase_Cmp{
    constructor(protected constants) {
        super(constants);
    }
}

将产生错误:

类"Hero_Cmp"错误地扩展了基类"StructureBase_Cmp">
属性"constants"在类型"StructureBase_Cmp"中是私有的,但在中不是键入"Hero_Cmp"。类Hero_Cmp

因为父级具有属性private,而子级具有属性protected。这没有道理。

只是让它也受到保护

export class StructureBase_Cmp {
    constructor(protected constants){ // also protected
    }
}
export class Hero_Cmp extends StructureBase_Cmp{
    constructor(protected constants) {
        super(constants);
    }
}

最新更新