无法从派生类-TypeScript访问/获取抽象(基类)属性的值



我有两个类-一个是抽象的,另一个是扩展的。在抽象类中,我有一些公共/受保护的属性,它们在构造函数中初始化。让它是抽象的Parent和Child扩展Parent

问题:

  1. 为什么,当我试图获取抽象类(如:super.somePropertyOfParent(的属性值时,它总是未定义的,但当我调用它(如:this.somePropertyOfParet(时,它有值?从逻辑上讲,超级构造函数总是首先被调用,所以这些字段应该首先被初始化。

  2. 我的Parent抽象类中有两个BehaviourSubject(countryValue,languageValue(,它们在构造函数中用一些"初始值"初始化。在OnInit方法的Child类中(它显然是在Parent构造函数之后调用的(,我订阅了Parent的BehaviourSubjects,比如:this.countryValue.subscribe(…(,它收到了"INITIAL"值。然后在Parent的类中,ngOnChange方法调用subject.next(…(,但Child没有收到新值。。。为什么?

p.S.如果将BehaviourSubject属性设置为STATIC并引用ClassName.properties,则一切正常。

请参阅以下代码:

@Directive()
export abstract class IbCustomElementComponent implements OnChanges{
@Input('data-country') country = '';
@Input('data-language') language = '';
public countryValue:BehaviorSubject<string>;
public languageValue:BehaviorSubject<string>;

protected constructor(public translateService: TranslateService) {
this.countryValue = new BehaviorSubject<string>('initial');
this.languageValue = new BehaviorSubject<string>('initial');
}
abstract customElementReady(changes: SimpleChanges): void;
ngOnChanges(changes: SimpleChanges) {
if (this.country && this.language) {
this.translateService.use(this.country.toLocaleLowerCase() + '-' + this.language);
this.customElementReady(changes);
this.countryValue.next(this.country);
this.languageValue.next(this.language);
}
}
}

export class CustomerCardsComponent extends IbCustomElementComponent implements OnInit {

displayedColumns: string[] = ['fieldName', 'value'];
CARD_DATA: CardData[][] = [];
dataSource = this.CARD_DATA;
cards: Card[] = [];
currentCustomer : Customer = new Customer();

constructor(private customerListService: CustomerListService, public override translateService: TranslateService) {
super(translateService);
}
ngOnInit(): void {
this.countryValue.subscribe(c=>{
this.currentCustomer.bic = Bic[c.toUpperCase()];
if(this.currentCustomer.bic){
this.getCustomerCards(this.currentCustomer)
}
})
}
}

首先,不能调用super.somePropertyOfParent的原因是,您的抽象类不是与派生类分开初始化的——派生类只是继承了抽象类的所有属性。这就是为什么您调用this而不是super

对于ngOnChanges方面,我相信发生的事情是没有调用抽象类的方法,因为据我所知,当涉及到继承的生命周期挂钩时,Angular组件/指令很烦人。我知道我过去有过OnInitOnDestroy的问题。

我会尝试在您的派生类中实现OnChanges,如下所示:

ngOnChanges(changes: SimpleChanges) {
super.ngOnChanges(changes);
}

因此,您只在引用父类的方法实现时使用super,而不用于子类自动继承的任何属性。

最新更新