When I use RoleGuard in my 'pre-harvest' children path and I open the browser the browser is totally blocked, it seems that is in an infinite loop. I don't have any compilation problem and I can't open the console to see what errors I have.
Is possible to use canActivate in children paths? or should I use CanActivateChild? I don't have this problem with CanActivateChild.
const preHarvestRoutes: Routes = [
{
path: '',
component: PrivateComponent,
canActivate: [AuthGuard],
children: [
{
path: 'pre-harvest',
component: PreHarvestComponent,
canActivate: [RoleGuard], <------- IF I REMOVE THIS I DO NOT HAVE ANY PROBLEM.
children: [
{
path: 'new-field',
component: NewFieldComponent
},
]
}
]
}
];
RoleGuard:
import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { UserRolesService } from '../services/user-roles.service';
import { webStorage } from "../utils/web-storage";
@Injectable()
export class RoleGuard implements CanActivate {
constructor(
private userRoles: UserRolesService
, private router: Router
) { }
canActivate( route: ActivatedRouteSnapshot, state: RouterStateSnapshot ) {
//let roles = route.data['roles'] as Array<string>;
//let rolesUserLogged = webStorage.user;
this.router.navigate( ['pre-harvest'] );
return true;
}
}
You are redirecting to the same route as to where the RoleGuard
is placed. This obviously results in an infinite loop. You should change your RoleGuard
to this:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
//let roles = route.data['roles'] as Array<string>;
//let rolesUserLogged = webStorage.user;
return true;
}
You still have to specify your RoleGuard logic, but the issue you are having is redirecting to the same route.