指定基类的OnDestroy时,派生类是否应显式调用它?

时间:2019-06-20 09:17:52

标签: angular

如果我有一个没有OnDestroy方法的派生服务类,而基类有一个,则销毁派生类时会隐式调用基类的OnDestroy方法吗?

export class DerivedService extends MyBaseClass {
   // ...
   // No OnDestroy method
}

export class MyBaseClass implements OnDestroy {
   OnDestroy() {
     // some code
   }
}

2 个答案:

答案 0 :(得分:1)

否,您需要显式调用BaseClass的ngOnDestroy(从ChildClass中)。为此,请在子组件ngOnDestroy方法中使用super保留关键字(以获取父类引用)。

ngOnDestroy() { return super.ngOnDestroy(); }

答案 1 :(得分:0)

是的,您可以尝试这样。

export class DerivedService extends MyBaseClass {
   // ...
   // here we are creating a object of our parent class
   parentClassRefObj = new MyBaseClass();
   constructor() {}
   // here is the function which is calling a parent class OnDestroy method
   myFun() {
      this.parentClassRefObj.OnDestroy();
   }
}

export class MyBaseClass implements OnDestroy {
   OnDestroy() {
     // some code
   }
}