Michael L.
Michael L.

Reputation: 272

Accessing component of the ActivatedRoute in the canActivate Guard

As far as I know the call signature of canActivate looks like this:

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {

}

I have a service that expects the name of a component and returns the necessary user role to access this component, so that I can check in the canActivate function of my guard, whether the active user has the corresponding role or not. My problem is, that I don't know how to access the component. After some googling I found solutions like this:

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
  const nameOfComponent = route.routeConfig.component.name;
  return doSomeRoleCheck(nameOfComponent);
}

But in my case I just get an error: "Cannot read proprty 'name' of undefined". How can I access the component of the active Route or especially the name as a string?

Edit

I found out, that I do check this guard on a parent route. When I check it in the child route it works. How can I access the child component from parent can ActivatedRouteSnapshot

Upvotes: 7

Views: 6770

Answers (1)

chrispy
chrispy

Reputation: 3612

Something like this would probably work in your case:

export abstract class RoleCheck {
  myRoles: string[];
}

@Component({ ... })
export class YourComponent extends RoleCheck {
  public myRoles = ['User', 'Admin'];
}

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
  if (!route.routeConfig.component instanceof RoleCheck) {
    //Throw
  }
  return doSomeRoleCheck(route.routeConfig.component.myRoles)
}

Upvotes: 7

Related Questions