1

I have a question about making http requests on beforeunload event. The window:beforeunload is a synchronous event, so if I perform an async action within the event listener the event is completed before my async action. That is why my http request is never made. I know that it is possible to use fetch API or navigator.sendBeacon method, but are there any built-in approaches or recommended 'angular' way for this functionality?

Here is an approach using async/await and angular httpClient, which is not working.

  @HostListener('window:beforeunload')
  async beforeUnload(): Promise<void>{
    await this.articleService.setArticlePersistence({});
  }
  • Your request is not cancelled simply because the event handler finishes running. Something else is cancelling your request. Share code so we can have a look. – Aviad P. Aug 23 '21 at 12:34
  • @AviadP. I have just updated the post. You can check. – Ivan Kroshko Aug 23 '21 at 13:34
  • My bad, I forgot that `beforeunload` happens just before the page is unloaded :) - your only hope is to warn the user that some data is not saved, have him cancel the unload, and then retry it when the async call is done. Check this SO question https://stackoverflow.com/questions/36763141/is-there-any-lifecycle-hook-like-window-onbeforeunload-in-angular2 – Aviad P. Aug 23 '21 at 13:50

0 Answers0