【问题标题】:Angular Authguard displays a blank pageAngular Authguard 显示一个空白页面
【发布时间】:2020-12-10 22:30:15
【问题描述】:

我在一些路由中使用 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;
  }

【问题讨论】:

    标签: angular auth-guard


    【解决方案1】:

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

    您可以订阅提供正确预期角色值的服务,然后相应地定义您的 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;
            }
    

    【讨论】:

    • 好吧,是的,这是有道理的。您能否提供一个简短的示例来说明 adminService 的外观?我更新了我的帖子并添加了我当前的 authService
    • 您可以在用户登录后将用户角色存储在本地存储或全局变量中,并使用存储的值来执行您的预期角色检查
    猜你喜欢
    • 2020-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-06
    • 2018-06-07
    • 1970-01-01
    相关资源
    最近更新 更多