简体   繁体   中英

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 => {

  });

}

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/

You can set expire time on server for the token. If you make next api call you will get 401 error. One option to catch error and redirect ist an interceptor:

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { const authHeader = this.getAuthorizationHeaders(req.headers); const authReq = req.clone({ headers: authHeader }); return next.handle(authReq) .pipe( catchError((error) => { if (error.status === 401) { this.localStorageService.removeItem('auth'); this.router.navigate(['/login']); return of({} as HttpEvent<any>); } return throwError(this.errorHandler.getError(error)); }) ); } 

You can store data with a var "time expiration" (your example is Date now + 2 min). After you read this data and check date.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM