简体   繁体   English

带会话存储的Angular 6

[英]Angular 6 with session Storage

I am using sessionStorage to save my user data. 我正在使用sessionStorage保存用户数据。 if your idle some time (ex:2min). 如果您空闲了一段时间(例如2分钟)。 i need to expire sessionStorage. 我需要使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. 您可以安装软件包ng2-idle并在onTimeout订阅中实现您的过期。

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/ 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. 如果您进行下一个api调用,则会收到401错误。 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). 您可以使用var“时间到期”来存储数据(您的示例是Date now + 2 min)。 After you read this data and check date. 读取此数据并检查日期之后。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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