timerangular16

How to show countdown for all angular pages without resetting


I have a timer for 10 minutes and I need to show it in my angular app that has many routing links (pages). I know that angular is one page site but you can browse to different areas by using routing. Since this is true, how to show the timer in the main app component for all the routing links without resetting the timer everytime i go to difffent routing link?

timer code:

typescript file:

timer(minute) {
    // let minute = 1;
    let seconds: number = minute * 60;
    let textSec: any = "0";
    let statSec: number = 60;

const prefix = minute < 10 ? "0" : "";

const timer = setInterval(() => {
  seconds--;
  if (statSec != 0) statSec--;
  else statSec = 59;

  if (statSec < 10) {
    textSec = "0" + statSec;
  } else textSec = statSec;

  this.display = `${prefix}${Math.floor(seconds / 60)}:${textSec}`;

  if (seconds == 0) {
    console.log("finished");
    clearInterval(timer);
  }
}, 1000);


}

html file:

{{display}}

if I put this in main app component and tried to go to different routing link it will reset the timer again and I don't want this to happened. Let us say main page is properties and second one is contacts, if i switch between then the timer resets again and again, I don't want that.


Solution

  • I found out that I can put that in app module and then add the following in my main page:

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

    this is will reload the page once and the timer will start. on logout i change the value to 2 again so that when logged in it is 2 again:

        onlogout()
      {
        // if (!sessionStorage.getItem('foo')) { 
        //   sessionStorage.setItem('foo', 'no reload') 
        //   window.location.reload() 
        // } else {
        //   sessionStorage.removeItem('foo')
        // }
        localStorage.setItem('theflag', '2')