Search code examples
javascriptangularsession-storage

Angular 6 with session Storage


I am using sessionStorage to save my user data. if your idle some time (ex:2min). i need to expire sessionStorage. how i expire it? can you give me small guidance.

login function

 signin() {

this.disableSubmit = true;
return this.loginservice.loginUser(this.model).subscribe(
  data => {

         if (data) {
              this.responseuser = data.response;
            ;
              if (data.response.responseCode === 200) {

                  window.sessionStorage.setItem('token', JSON.stringify(this.responseuser));
                  window.sessionStorage.setItem('isLoggedIn', 'true');

                  }

            }


},
  error => {

  });

}


Solution

  • You can install package ng2-idle and implement your expire in onTimeout subscribe.

    This is sample source code

    this.idle.onTimeout.subscribe(() => {
    
              this.idleState = 'Timed out!';
              this.timedOut = true;         
              this.idle.stop();
              //prevent init multiple time
              this.idle.onTimeout.observers.length = 0;
              this.idle.onIdleStart.observers.length = 0;
              this.idle.onIdleEnd.observers.length = 0;
    
              // add your code to expire session storage here
            });
    

    https://hackedbychinese.github.io/ng2-idle/