I'm using AuthGuard for some of my routes:
{
path: "dashboard",
component: DashboardComponent,
pathMatch: "full",
canActivate: [RoleGuardService],
data: {
expectedRole: Role.ROLE_ADMIN,
},
},
And my 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;
}
}
If I log into the application and then use the UI to navigate to the dashboard everything works as expected. If I enter the URL in the browser localhost:4200/dashboard
I get a blank page.
What am I missing?
Edit: typo
Edit: this is my current authService:
public hasRole(r: string): boolean {
let hasRole = false;
this.getCurrentRoles().forEach((role) => {
if (role.authority === r) {
hasRole = true;
}
});
return hasRole;
}
In case of directly hitting the URL your expectedRole will be always false and since you have not provided any router.navigate for false condition therefore you get the blank page.
You can subscribe to the service which gives the correct value of expectedRole and than define your if statement conditions accordingly. This would work in all cases.
For Example:
Service:
Inside Guard: