angular - Angular Router 路由保护 CanActivate 总是返回 false
问题描述
我曾经CanActivate
保护一个页面,但它总是返回 false,因为我无法访问受保护的路由器。我尝试了很多方法,但未能成功解决问题。我是 Angular 的新手,如果(data.hasPermission == true),我一直在验证条件。
谁能帮帮我吗?
auth.service.ts
//Checking user access
getUserAccess(name: string): Observable<any> {
return this.http.get(`api/${name}/useraccess`).pipe(
map(
(response: any) => {
return response;
},
),
);
};
checkUserPermission() {
this.getUserAccess(this.name).subscribe(data => {
this.hasaccess = false;
if (data.hasPermission == true) {
this.hasaccess = true;
} else {
this.hasaccess = false;
}
});
return this.hasaccess
}
isUserHasAccess(): boolean {
return this.hasaccess
}
auth.guard.ts
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
if (this.authService.isUserHasAccess()) {
return true;
} else {
return false;
}
}
{"hasPermission":true}
解决方案
您正在返回一个静态值,而不是等待异步任务完成。
仔细查看文档,canActivate
也可以返回Observable
解析为true
or的false
,这允许您进行异步检查。
试试这个:
checkUserPermission() {
return this.getUserAccess(this.name).pipe(map(data => data.hasPermission === true))
}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
return this.authService.checkUserPermission();
}
AngularRouter
将订阅它Observable
,您不必这样做。您所要做的就是将它映射到一个返回布尔值的函数。
推荐阅读
- swift - Swift - Google AdMob 根本不提供广告
- haskell - 连续列表元素的 Haskell 模式匹配
- c# - 将自定义上下文添加到登录页面身份服务器 4
- javascript - 有没有一种有效的方法可以在 Javascript 中创建图像数组,而无需将每个单独的图像添加到数组中?
- mysql - 如何在nodejs中处理mysql select查询返回的数据
- html - 我怎样才能让我自定义字体真棒图标?
- algorithm - 给定一组要拼接的索引,生成删除每个元素的顺序
- javascript - Javascript 正则表达式以匹配以给定模式开头的代码块
- android-management-api - 从 Android Device Policy 获取设备标识符
- td-engine - 使用idea的UI从tdengine查询数据,时间戳会丢失毫秒