Angular Router 路由守卫 CanActivate 总是返回 false

时间:2021-06-11 18:18:12

标签: angular angular-router canactivate

我使用 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;
    }
}
来自 API

的 json 数据

{"hasPermission":true}

1 个答案:

答案 0 :(得分:1)

您返回的是静态值,而不是等待异步任务完成。

仔细查看文档,canActivate 还可以返回解析为 Observabletruefalse,这允许您进行异步检查。

试试这个:

checkUserPermission() {
    return this.getUserAccess(this.name).pipe(map(data => data.hasPermission === true))
}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    return this.authService.checkUserPermission();
}

Angular Router 将订阅该 Observable,您不必这样做。你所要做的就是将它映射到一个返回布尔值的函数。