我们有一个 Router Guard,它检查用户是否登录和管理 它还应该检查我们发送到服务器的请求是否有正确的结果。
问题是 canActivate 函数在服务器请求完成之前完成,因此 Router Guard 始终为 false。
我希望你能解决这个问题
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
var user = JSON.parse(localStorage.getItem('currentUser'));
if (user != null&&!user.isNotAdmin) {
if(this.userService.isLoggedIn(user)){
return true;
}else{
return false;
}
}else{
// not logged in so redirect to login page with the return url
this.router.navigate([''], { queryParams: { returnUrl: state.url } });
return false;
}
最佳答案
您必须使用 async/await
来确保 canActivate 等到您的服务器请求得到解决。这里有一些示例代码可以帮助您:
/* UserService */
isLoggedIn(user): Observable<boolean> {
// check if user is logged in
return isUserLoggedIn;
}
/* Guard */
async canActivate(route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Promise<boolean> {
const user = JSON.parse(localStorage.getItem('currentUser'));
if (user !== null && !user.isNotAdmin) {
const isUserLoggedIn: boolean = await this.userService.isLoggedIn(user).toPromise();
// toPromise() converts Observable to Promise (async/await only works on Promises)
// the code 'waits' at the above line till the server request is resolved
return isUserLoggedIn;
} else {
// not logged in so redirect to login page with the return url
this.router.navigate([''], { queryParams: { returnUrl: state.url } });
return false;
}
如果您想进一步阅读,请引用:
关于Angular 异步路由器守卫,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49130997/