Reputation: 439
There have already been written lots of stuff about unsubscribing from observables in standard Angular workflow, but not so much about unsubscribing on page refresh (at least I haven't found much).
So, what can be done with subscriptions which should be unsubscribed in ngOnDestroy
(which is never called on page refresh)? The only material I came across during investigation was this, it uses javascript onbeforeunload
function.
ngOnInit(){
//Some stuff
window.onbeforeunload = () => this.ngOnDestroy();
}
ngOnDestroy(){
//Some stuff
}
This is quite an old answer, so maybe some things have moved further - is there currently any 'more Angular' way how to handle such subscriptions on page refresh?
Upvotes: 2
Views: 1037
Reputation: 4182
As @LucaAngrisani mentions, you do not have to call ngOnDestroy
if you just unsubscribe observables in ngOnDestroy
.
If you have to call ngOnDestroy
for some reasons on browser reload,
a more angular way is to use @HostListener
.
@HostListener('window:beforeunload', ['$event'])
beforeUnload(e: Event) {
this.ngOnDestroy();
}
Upvotes: 1
Reputation: 399
You don't need to unsubscribe on page refresh because your entire app reloading and no longer subscription are active. Your component is reloaded and (if you are some subscription in your component loaded) new subscription are provided
Upvotes: 5