如果用户对象为空,我已经更改了我的 authguard 以获取用户对象。我只是将令牌存储在存储中。我看到console.log“角色和用户正常”和正确的url /member,但它总是将我重定向到/而不是/member。
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
if (this.authService.loggedin) {
if (!this.authService.user) {
console.log('get user')
this.authService.getUser().pipe(first()).subscribe((result: any) => {
console.log(result.user)
if (route.data.roles && route.data.roles.indexOf(result.user.role.name) === -1) {
console.log('wrong role')
this.router.navigate(['/']);
return false;
} else {
console.log('role and user ok')
console.log(state.url)
return true;
}
});
} else {
console.log(this.authService.user)
console.log('user already set')
if (route.data.roles && route.data.roles.indexOf(this.authService.user.role.name) === -1) {
console.log('WRONG ROLE')
this.router.navigate(['/']);
return false;
} else {
console.log('user and role ok')
return true;
}
}
} else {
console.log('redirect to login')
this.router.navigate(['/login']);
return false;
}
}
身份验证服务
public isLoggedIn() {
if (localStorage.getItem('token')) {
return true;
} else {
return false;
}
}
getUser() {
return this.http.get<any>(environment.apiUrl + '/user').pipe(
tap(res => this.setSession(res))
);
}
谢谢