I have a requirement where based on role I need to activate to the route. Please find code below:
canActivate(): boolean {
if(this.login_token) {
this._Service.getUser(this.login_token).subscribe(
(data) => {
if(data.role === 'admin') {
return true;
}
});
} else {
return false;
}
}
And I have configured my route as shown below:
{path: 'user', children: childRoutes, canActivate: [AuthGuard]}
But even if my guards return to true still I am not able to route to user
route. Please let me know if I am doing something wrong here. I have already explored lot of posts on SO to handle async call in guards but still no suucess
You're making an http call at every route change ?
When you have a token in your front-end, it's better to either
If you make an http call at every route change, not only this will slow down your application, but mobile data users will have to pay for those calls and they won't like that.
What you should do instead is :
canActivate(): boolean {
return this.login_token ? true : false;
}
If your backend is handling wrong tokens, or
canActivate(): boolean {
try {
return this.isTokenValid();
} catch(error) {
return false;
}
}
isTokenValid(): boolean {
// Test if token exists
// Decode token
// Check if token is not expired
// return a boolean stating if it succeed
}
If your backend doesn't handle tokens (but it should so ...)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.