我使用 CanActivate
来保护页面,但它总是返回 false,因为我无法访问受保护的路由器。我尝试了很多方法,但都没有成功解决问题。我是 angular 的新手,我一直在验证条件 if (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}
答案 0 :(得分:1)
您返回的是静态值,而不是等待异步任务完成。
仔细查看文档,canActivate
还可以返回解析为 Observable
或 true
的 false
,这允许您进行异步检查。
试试这个:
checkUserPermission() {
return this.getUserAccess(this.name).pipe(map(data => data.hasPermission === true))
}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
return this.authService.checkUserPermission();
}
Angular Router
将订阅该 Observable
,您不必这样做。你所要做的就是将它映射到一个返回布尔值的函数。