I have a angular 4 application. There i use JWT token for authentication purposes. Everything works fine. but the token expiration time i have given to the JWT token is 1 hour.
you can check if the token is expired or not and as a response, you can redirect to login page store token in local storage for example
yourmthod(parametr) {
this.token = localStorage.getItem("token");
this.headers = new Headers();
this.headers.delete(this.token);
this.headers.append("Authorization", this.token);
return this._http.post(Constants.SERVER_URL + 'your method', {headers: this.headers});
}
so it will response 401 error and you can handle this by redirecting to your login page
if any query you can ask a question in comments so I can help you
and you can also use if-else in your method
and you can write code in app.component.ts in onIt()
method
ngOnInit(): void {
let token = localStorage.getItem("token");
if (token) {
this.isTokenAvaialable = true;
this.http.get(Constants.SERVER_URL + 'your mthod to validate token' + token).subscribe(data => {
if (data == true) {
if (window.location.pathname == "") {
this.router.navigate(['/home', {outlets: {'r2': ['dashboard']}}]);
}
} else if (data == false) {
this.logout('Server restarted.Please login again!!');
} else {
this.logout('Session expired.Please login again.!!');
}
}, (err: HttpErrorResponse) => {
this.toastr.warning('Server restarted.Please login again!!', 'Alert');
localStorage.removeItem("token");
this.isTokenAvaialable = false;
this.logout('Server restarted.Please login again!!');
});
} else {
this.isTokenAvaialable = false;
this.router.navigate(['']);
localStorage.removeItem("token");
this.isTokenAvaialable = false;
}
}