[英]Unable to access/get value of abstract (base) class properties from derived class - TypeScript
我有 2 個類 - 一個是抽象的,另一個類正在擴展它。 在 ABSTRACT 類中,我有一些在構造函數中初始化的公共/受保護屬性。 讓它是抽象的 Parent 和 Child 擴展 Parent
問題:
為什么,當我試圖獲取抽象類的屬性值時:super.somePropertyOfParent 它總是未定義的,但是當我這樣稱呼它時:this.somePropertyOfParent 它有值? 從邏輯上講,超級構造函數總是首先被調用,所以這些字段應該首先被初始化。
我的 Parent 抽象類中有 2 個 BehaviourSubjects (countryValue, languageValue),它們在構造函數中用一些“初始值”進行了初始化。 在 OnInit 方法的 Child 類中(顯然在 Parent 構造函數之后調用),我訂閱了 Parent 的 BehaviourSubjects,例如:this.countryValue.subscribe(...) 並且它接收到“INITIAL”值。 然后在Parent類的ngOnChange方法調用subject.next(...),但是Child沒有收到新值...為什么?
PS 如果將 BehaviourSubject 屬性設為 STATIC 並參考 ClassName.property - 一切正常。
請看下面的代碼:
@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 組件/指令在繼承的生命周期掛鈎方面很煩人。 我知道我過去曾遇到過OnInit
和OnDestroy
的問題。
我會嘗試在您的派生類中實現OnChanges
,如下所示:
ngOnChanges(changes: SimpleChanges) {
super.ngOnChanges(changes);
}
因此,只有在引用父類的方法實現時才使用super
,而不是子類自動繼承的任何屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.