【问题标题】:Angular Router route guard CanActivate always returns falseAngular Router 路由保护 CanActivate 总是返回 false
【发布时间】:2021-08-28 16:21:50
【问题描述】:

我使用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}

【问题讨论】:

    标签: angular angular-router canactivate


    【解决方案1】:

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

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

    试试这个:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-29
      • 2016-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-12
      • 2021-04-30
      相关资源
      最近更新 更多