将参数传递给路由守卫 [英] Pass parameter into route guard
问题描述
我正在开发一个应用程序,它有很多角色,我需要使用守卫来阻止导航到基于这些角色的应用程序部分.我意识到我可以为每个角色创建单独的守卫类,但宁愿有一个我可以以某种方式传递参数的类.换句话说,我希望能够做类似的事情:
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屋!