0

I wont to save user data on exit/reload page:

@HostListener('window:beforeunload', ['$event']) async unloadHandler() {
    await this.api.saveUserSettings(this.userSetting);
}

It is sometime work, and sometime not. in chrome network i see that the request always canceled.

yantrab
  • 2,482
  • 4
  • 31
  • 52
  • If you are ok with the blocking action - you could follow the answer here - https://stackoverflow.com/questions/35922071/warn-user-of-unsaved-changes-before-leaving-page – dmoo Jun 03 '19 at 11:31
  • 1
    @dmoo a deactivate guard isn't a blocking action. `window.alert` is a blocking action. –  Jun 03 '19 at 11:36
  • @Maryannah yup, was referring to the highest rated 'answer' with its use of confirm, not the ticked answer :) – dmoo Jun 03 '19 at 11:44
  • 1
    @dmoo It's just that they way commented seems to say that the answer is to use a guard, and that the guard is blocking. I just stated that to not confuse the future readers :) –  Jun 03 '19 at 11:45

1 Answers1

0

Because you can't stop a user from leaving the page with a non blocking action.

Instead of doing that, you should save the settings in your local storage

@HostListener('window:beforeunload', ['$event']) async unloadHandler() {
  localStorage.setItem('settings', this.userSetting);
}

And use a resolver or an application initializer to make your request once the page is reloaded.