簡體   English   中英

帶會話存儲的Angular 6

[英]Angular 6 with session Storage

我正在使用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 => {

  });

}

您可以安裝軟件包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/

您可以在服務器上為令牌設置過期時間。 如果您進行下一個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)); }) ); } 

您可以使用var“時間到期”來存儲數據(您的示例是Date now + 2 min)。 讀取此數據並檢查日期之后。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM