Angular Authguard显示一个空白页
我正在使用AuthGuard进行我的一些路线:Angular Authguard显示一个空白页,angular,auth-guard,Angular,Auth Guard,我正在使用AuthGuard进行我的一些路线: { path: "dashboard", component: DashboardComponent, pathMatch: "full", canActivate: [RoleGuardService], data: { expectedRole: Role.ROLE_ADMIN, }, }, 还有我的角色守卫 @Injectable()
{
path: "dashboard",
component: DashboardComponent,
pathMatch: "full",
canActivate: [RoleGuardService],
data: {
expectedRole: Role.ROLE_ADMIN,
},
},
还有我的角色守卫
@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导航到仪表板,则一切正常。如果我在浏览器localhost:4200/dashboard
中输入URL,我会得到一个空白页面
我错过了什么
编辑:打字错误
编辑:这是我当前的authService:
public hasRole(r: string): boolean {
let hasRole = false;
this.getCurrentRoles().forEach((role) => {
if (role.authority === r) {
hasRole = true;
}
});
return hasRole;
}
在直接命中URL的情况下,你的预期目标总是错误的,因为你没有提供任何路由器。导航错误的条件,因此你得到空白页。
您可以订阅提供正确expectedRole值的服务,然后相应地定义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;
}
好的,是的,这是有道理的。你能提供一个简单的例子来说明adminService是什么样子的吗?我更新了我的帖子并添加了我当前的authServiceYou可以在用户登录并使用存储的值执行ExpectedRole检查后将用户角色存储在本地存储或全局变量中
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;
}