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
  • 27,782
  • 43
  • 120
  • 210
Crocsx
  • 2,356
  • 1
  • 25
  • 41

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,167
  • 2
  • 17
  • 36
  • 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