首页 > 解决方案 > Angular Authguard 显示一个空白页面

问题描述

我正在为我的一些路线使用 AuthGuard:

  {
    path: "dashboard",
    component: DashboardComponent,
    pathMatch: "full",
    canActivate: [RoleGuardService],
    data: {
      expectedRole: Role.ROLE_ADMIN,
    },
  },

还有我的 roleguard.service

@Injectable()
export class RoleGuardService implements CanActivate {
  constructor(public auth: AuthService, public router: Router) {}

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): boolean {
    const expectedRole = route.data.expectedRole;
    if (!this.auth.hasRole(expectedRole)) {
      this.router.navigate(["login"], {
        queryParams: { returnUrl: state.url },
      });
      return false;
    }
    return true;
  }
}

如果我登录应用程序,然后使用 UI 导航到仪表板,一切都会按预期工作。如果我在浏览器中输入 URL,localhost:4200/dashboard我会得到一个空白页面。

我错过了什么?

编辑:错字

编辑:这是我当前的 authService:

  public hasRole(r: string): boolean {
    let hasRole = false;
    this.getCurrentRoles().forEach((role) => {
      if (role.authority === r) {
        hasRole = true;
      }
    });
    return hasRole;
  }

标签: angularauth-guard

解决方案


如果直接点击 URL,您的 expectedRole 将始终为 false,并且由于您没有为 false 条件提供任何 router.navigate,因此您会得到空白页。

您可以订阅提供正确预期角色值的服务,然后相应地定义您的 if 语句条件。这适用于所有情况。

例如:

服务:

  private isAdmin = new BehaviorSubject<boolean>(this.checkForAdmin());
  isUserAdmin = this.isAdmin.asObservable();

  checkForAdmin():boolean
  {
    const userName = localStorage.getItem("userName");

    if(userName == "Admin") //Replace with your expectedRole check
    {
      return true
    }
    return false;

  }

内卫:

this.adminService.iAdmin.subscribe(result=>this.userAdmin=result)
        if (this.userAdmin) {
    
          return true;
        }
        else
        {
          console.log('Could not authenticate Admin');
       
       // to the desired or default page

          this.router.navigate(['dashboard'],{queryParams:{'redirectURL':state.url}});
          //return false;
        }

推荐阅读