将参数传递到路径防护中 [英] Pass parameter into route guard

查看:58
本文介绍了将参数传递到路径防护中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个具有很多角色的应用程序,我需要使用警卫来根据这些角色阻止对应用程序各部分的导航.我意识到我可以为每个角色创建单独的后卫类,但宁愿拥有一个可以以某种方式将参数传递给它的类.换句话说,我希望能够执行以下操作:

I'm working on an app that has a lot of roles that I need to use guards to block nav to parts of the app based on those roles. I realize I can create individual guard classes for each role, but would rather have one class that I could somehow pass a parameter into. In other words I would like to be able to do something similar to this:

{ 
  path: 'super-user-stuff', 
  component: SuperUserStuffComponent,
  canActivate: [RoleGuard.forRole('superUser')]
}

但是,由于您所传递的只是警卫的类型名称,因此无法考虑实现此目标的方法.我是否应该只是硬着头皮,为每个角色编写单独的后卫班级,而转而使用单个参数化类型来代替我的优雅幻想?

But since all you pass is the type name of your guard, can't think of a way to do that. Should I just bit the bullet and write the individual guard classes per role and shatter my illusion of elegance in having a single parameterized type instead?

推荐答案

您可以执行以下操作,而不是使用forRole():

Instead of using forRole(), you can do this:

{ 
   path: 'super-user-stuff', 
   component: SuperUserStuffComponent,
   canActivate: RoleGuard,
   data: {roles: ['SuperAdmin', ...]}
}

并在您的RoleGuard中使用它

and use this in your RoleGuard

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot)
    : Observable<boolean> | Promise<boolean> | boolean  {

    let roles = route.data.roles as Array<string>;
    ...
}

这篇关于将参数传递到路径防护中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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