I'm facing a dilemma with my Observable in the root Angular (6.x) component, AppComponent
.
Typically, I would unsubscribe from any open Subscription when calling destroy() using the lifecycle hook, ngOnDestroy
.
However, since the AppComponent serves as the application's root and is only destroyed when the entire application shuts down, I am unsure if it is necessary to implement ngOnDestroy and bother with unsubscribing from Subscriptions.
The exact solution to this seemingly common scenario has eluded me.
For example:
export class AppComponent implements OnInit, OnDestroy {
private tokenSubscription: Subscription;
constructor(private dataSvc: DataService) { }
ngOnInit() {
this.tokenSubscription = this.dataSvc.myObservable.subscribe((val) => {
// do stuff
});
}
ngOnDestroy() {
this.tokenSubscription.unsubscribe(); // Do I need this in the root component?
}
}
Any insights are greatly appreciated!