angular - 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;
}
解决方案
如果直接点击 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;
}
推荐阅读
- boost - 实现一个 BOOST_TEST test_runner 来运行来自不同共享库的多个测试
- android - 禁用剪贴板选项 Edittext
- excel - 谷歌表格使用当前表格中计算的动态值引用另一张表格中的值
- javascript - 请求后打开模式 - Vue.js
- python - 使用 isspace() 测试索引值的代码输出错误
- .net - 如何限制 dotCover 在多目标构建中仅分析一组程序集?
- python - 在 Python ElementTree 中忽略大小写 findall
- python - 如何使 Scrapy 通用?
- webhooks - 已创建 Webhook,但从未命中回调
- terraform - Terraform-12 (AWS):根据提供的输入变量使用 for/for_each 创建子网