I'm guarding some of my component with AuthGuard, and some are not. Which is, it can be accessed although the user not logged in yet.
On that component, I want to show some difference on the UI between the logged in user and not logged in user. For example, the logged in user will be shown "Logout" menu in the sidebar, while not logged in user will be shown "Login" menu. So I need to get the canActivate value (or the status whether the user has logged in or not) on my component.
And this is my AuthGuard file :
@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
constructor(
private router: Router,
private authenticationService: AuthenticationService
) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
const currentUser = this.authenticationService.currentUserValue;
if (currentUser) {
// check if route is restricted by role
if (route.data.roles && route.data.roles.indexOf(currentUser.role) === -1) {
// role not authorised so redirect to home page
this.router.navigate(['/']);
return false;
}
// authorised so return true
return true;
}
// not logged in so redirect to login page with the return url
this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } });
return false;
}
}
I'm searching and asking to some sources and they said it can't be done. But probably you can tell the alternate way to do that
解决方案之一是使用定义用户是否通过身份验证的方法创建服务,并在AuthGuard和任何组件中使用此方法
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.