Reputation: 937
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.
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 => {
});
}
Upvotes: 1
Views: 1484
Reputation: 7
You can store data with a var "time expiration" (your example is Date now + 2 min). After you read this data and check date.
Upvotes: 0
Reputation: 79
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));
})
);
}
Upvotes: 0
Reputation: 18975
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/
Upvotes: 2