Navigating in Guard in Angular5

There are some cases when we need to navigate in a Guard rather than in component. Why? Well, obviously you didn't have to define a component where you need to navigate. An example use case would be a route where you need to navigate given a certain role.

A sample route:

{
path: 'bride',
canLoad: [AuthGuard],
loadChildren: 'app/module/bride/bride.module#BrideModule'
}
A matching guard that navigates defending on role:

@Injectable()
export class AuthGuard implements CanActivate {

constructor( private router: Router, private route: ActivatedRoute ) {

}

canActivate( next: ActivatedRouteSnapshot, state: RouterStateSnapshot ): Observable | Promise | boolean {
console.log( 'registration.guard' )

if ( !KeycloakService.auth.loggedIn || !KeycloakService.auth.authz.authenticated ) {
return false;
}

//check group
if ( KeycloakService.hasGroup( 'Anime' ) ) {
this.router.navigate( ['/bride/postRegistration'] );

} else if ( KeycloakService.hasGroup( 'Vendor' ) ) {
this.router.navigate( ['/bride/postRegistration'] );
}

return true;
}
}

0 nhận xét:

Đăng nhận xét