Angular 6与会话存储

问题描述 投票:0回答:3

我正在使用sessionStorage来保存我的用户数据。如果你闲着一段时间(例如:2分钟)。我需要使sessionStorage过期。我怎么过期了?你能给我一些小指导吗?

登录功能

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

  });

}

javascript angular session-storage
3个回答
2
投票

你可以安装包ng2-idle并在onTimeout订阅中实现你的到期。

这是示例源代码

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/


0
投票

您可以在服务器上为令牌设置过期时间。如果您进行下一次api通话,您将收到401错误。捕获错误和重定向的一个选项是拦截器:

  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));
                })
            );
    }

0
投票

您可以使用var“time expiration”存储数据(您的示例是Date now + 2 min)。阅读此数据并检查日期后。

© www.soinside.com 2019 - 2024. All rights reserved.