在 canActivate Guard 中访问 ActivatedRoute 的组件 [英] Accessing component of the ActivatedRoute in the canActivate Guard

查看:26
本文介绍了在 canActivate Guard 中访问 ActivatedRoute 的组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,canActivate 的调用签名是这样的:

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

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {

}

我有一个服务,它需要一个组件的名称并返回访问该组件所需的用户角色,这样我就可以在我的守卫的canActivate函数中检查活动用户是否有相应的角色与否.我的问题是,我不知道如何访问该组件.经过一番谷歌搜索后,我找到了这样的解决方案:

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?

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

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

推荐答案

这样的事情可能适用于您的情况:

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

这篇关于在 canActivate Guard 中访问 ActivatedRoute 的组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆