在 canActivate Guard 中访问 ActivatedRoute 的组件

Accessing component of the ActivatedRoute in the canActivate Guard

据我所知 canActivate 的调用签名如下所示:

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {

}

我有一个服务需要组件的名称和 returns 访问该组件所需的用户角色,这样我就可以检查我的守卫的 canActivate 功能,是否活跃用户是否具有相应的角色。 我的问题是,我不知道如何访问该组件。经过一番谷歌搜索后,我找到了这样的解决方案:

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

但就我而言,我只是收到一个错误:"Cannot read proprty 'name' of undefined"。如何访问活动路由的组件,尤其是字符串形式的名称?

编辑

我发现,我确实在父路由上检查了这个守卫。当我在子路线中检查它时,它起作用了。如何从父组件访问子组件 ActivatedRouteSnapshot

类似这样的方法可能适用于您的情况:

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)
}