I find myself with a collection of components that share similar lifecycle logic, so I decided to create a base component that implements the OnDestroy interface.
abstract class BaseComponent implements OnDestroy {
subscriptions = new Array<Subscription>();
get model() { return … }
ngOnDestroy() {
for (let s of subscriptions) s.unsubscribe();
}
}
The issue arises when a developer writes a custom onDestroy method in a concrete Component that extends ComponentBase, as there is no clear indication that they need to call super.ngOnDestroy();
Is there a way in TypeScript to provide a warning for this? Or is there another design pattern besides component inheritance? perhaps a unit test could be written to verify ngOnDestroy on all components extending from BaseComponent?
EDIT I have come to realize that the BaseComponent with an array of subscriptions mentioned above is not a good practice and should be avoided. It would be better to use auto-unsubscribing observables.
Take a look at the takeUntil(destroy$) pattern:
class MyComponent implements OnInit, OnDestroy {
destroy$ = new Subject();
constructor(http: HttpService) { }
ngOnInit() {
http.get(...).pipe(
takeUntil(this.destroy$)
).subscribe(...);
}
ngOnDestroy() {
destroy$.next();
}
}