我正在使用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
});
您可以在服务器上为令牌设置过期时间。如果您进行下一次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“time expiration”存储数据(您的示例是Date now + 2 min)。阅读此数据并检查日期后。