首页 > 解决方案 > 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;
    }
}
来自 API 的 json 数据

{"hasPermission":true}

标签: angularangular-routercanactivate

解决方案


您正在返回一个静态值,而不是等待异步任务完成。

仔细查看文档,canActivate也可以返回Observable解析为trueor的false,这允许您进行异步检查。

试试这个:

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

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


推荐阅读