0

I am using some EventSource in a service in my APP.

I would like to close all the connection when the browser is closed/refreshed.

I have seen this post

Right now, this is what I added to my service.

  @HostListener('window:beforeunload')
  onBrowserClose() {
    this.clearAll();
  }

  clearAll() {
    if (this.eventSource) {
      this.eventSource.close();
    }
    this.callbacks = new Map<string, (e: any) => void>();
  }

is there a better solution ?

Muhammad Hewedy
  • 29,102
  • 44
  • 127
  • 219
Crocsx
  • 2,534
  • 1
  • 28
  • 50

1 Answers1

3

you can use ngOnDestroy() for unsubscribing events

ngOnDestroy() {
  if (this.eventSource) {
    this.eventSource.close();
  }
  this.callbacks = new Map<string, (e: any) => void>();
}

I would like to close all the connection when the browser is closed/refreshed.

this angular life cycle method will be called when component is going to destroy
Ganesh
  • 5,808
  • 2
  • 21
  • 41
  • 1
    this supposedly doesn't work https://stackoverflow.com/questions/40468267/angular-2-does-ngondestroy-get-called-on-refresh-or-just-when-navigate-away-fr since the component is not destroyed in angular workflow when you close the browser or refresh the page – Crocsx Jun 04 '19 at 07:46