1

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?

Frimlik
  • 357
  • 3
  • 15

2 Answers2

4

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

Luca Angrisani
  • 359
  • 3
  • 13
  • I see, the old subscription is not active anymore, but does it stay in memory? Isn't it a memory leak? – Frimlik Nov 09 '22 at 08:40
  • It is not a memory leak because subscriptions are linked to your app. Angular provide a SPA (Single Page Application) so the context of all app is gone on page reload – Luca Angrisani Nov 09 '22 at 08:46
  • Are you sure of that? If yes, everything is alright. I was just afraid about subscribing again and again while refreshing page and never unsubscribing... – Frimlik Nov 09 '22 at 08:56
  • Yes. It could help: https://blog.angular-university.io/why-a-single-page-application-what-are-the-benefits-what-is-a-spa/ – Luca Angrisani Nov 09 '22 at 09:08
1

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();
}
N.F.
  • 3,844
  • 3
  • 22
  • 53