Home > OS >  Angular: Unsubscribe on page refresh
Angular: Unsubscribe on page refresh

Time:11-09

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?

CodePudding user response:

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

CodePudding user response:

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();
}
  • Related