0

I want to hit an API to set the last active time of the user. But the API is not hitting. As time is taken by the API to initialize and hit the server and before the API hit starts, the application got closed

I tried this code in my app.component.ts file

    @HostListener('window:beforeunload', [ '$event' ])
      beforeUnloadHander(event) {
        this._apiService.setLastActive({time:new Date().getTime()/1000})
          .subscribe(data => {
          },err=> {
          })
      }

Can anybody suggest when can I call the API to set the last active status of the user?

Tony Ngo
  • 19,166
  • 4
  • 38
  • 60
  • Try this: beforeUnloadHander(event) { this._apiService.setLastActive({time:new Date().getTime()/1000}) .subscribe(data => { return true },err=> { }); return false; } more info here: https://stackoverflow.com/questions/2229942/how-to-block-users-from-closing-a-window-in-javascript – Jacopo Sciampi May 16 '19 at 06:54
  • It prompts the user to leave the site. is there some other way without prompting the user. And it didn't work when I closed the browser – PRABHJOT SINGH May 16 '19 at 07:29
  • You might want to look into some solution using polling, because relying on code to run before closing can cause problems. What if the browser/computer shuts down unexpectedly? – Scuba Kay May 16 '19 at 07:49

3 Answers3

1

Please use ngOnDestroy() Inside the component.ts file of the exiting component.

Features
It clean up just before Angular destroys the directive/component. Unsubscribe Observables and detach event handlers to avoid memory leaks and called just before Angular destroys the directive/component.https://angular.io/guide/lifecycle-hooks

If you have unsaved changes. try this stackoverflow answer Confirmation before closing of tab/browser

Sami Haroon
  • 869
  • 10
  • 14
0

Just came across this: https://stackoverflow.com/a/54920520/982517. Seems like beforeunload doesn't support async, so you will have to use XMLHttpRequest to call your API.

From the other post:

window.addEventListener("beforeunload", function (event) {
  var client = new XMLHttpRequest();
  client.open("POST", "http://url/to/endsession", false); // third parameter indicates sync xhr
  client.setRequestHeader("Content-Type", "application/json");
  client.send('{userId: "42"}');
  console.log('done!!!'); // outputs when a response is received 
});
Scuba Kay
  • 2,004
  • 3
  • 26
  • 48
0

Use javascript code, May be it will work for you.

window.onbeforeunload = e => {
    e.returnValue = 'Do you really want to leave this site?';
    return dialogText;
};