taleen wahdan
taleen wahdan

Reputation: 55

How to run code before exit angular application?

I am trying to add something in local storage when the user exit the angular app without pressing logout (close tab or browser).

Here is what I tried:

   @HostListener('window:UnloadHander', ['$event'])
    beforeUnloadHander(event:any) {
    return localStorage.setItem("theflag","2");
  }

it is not working, how to make it work?

Upvotes: 0

Views: 382

Answers (1)

taleen wahdan
taleen wahdan

Reputation: 55

I found the solution. In my main component I have:

if ((localStorage.getItem("theflag") === "2") && (sessionStorage.getItem("userName")))
{
  localStorage.setItem("theflag","1");
  window.location.reload();
}

so I will check for the flag which is equal to 2 when I logout so when logged in the condition is true and the page will reload once since the value will change to 1.

then after that I have the following that will execute if we close the window or tab.

this.context = this;
window.addEventListener("beforeunload", function (e) {
    this.localStorage.setItem("theflag","2");
});

which will move the flag back to 2.

in my logout I have also changed the value to 2.

    onlogout()
  {
    localStorage.setItem('theflag', '2')

and that is it. That is the walk around that I found useful for this situation.

Upvotes: 0

Related Questions