简体   繁体   English

Angular2路由器CanActivate,带参数?

[英]Angular2 Router CanActivate, with Parameters?

i've seen some issues on this specific issue. 我在这个具体问题上看到了一些问题。

I'm lately only working on angular2 projects. 我最近只处理angular2项目。 Anyhow I'm rolling into an issue right now. 无论如何我现在正在讨论一个问题。 In the deprecated Router I added my User Role in the data part of the route, I had overriden the routerOutlet so I could check this value before activating a route). 在已弃用的路由器中,我在路由的数据部分添加了用户角色,我已经覆盖了routerOutlet,因此我可以在激活路由之前检查此值)。

Currently we can conform to the CanActivate Class/Interface row w/e we can call it. 目前我们可以使用CanActivate类/接口行,我们可以调用它。

Right now I would like to be able to provide Permissions (which I've slapped into an Enum) to such CanActivate classes. 现在我希望能够为这样的CanActivate类提供权限(我已经打成了Enum)。 Before I was simply checking if the user was logged in by accessing my SessionService, I however now need to check if a user has certain permissions. 在我通过访问我的SessionService来检查用户是否已登录之前,我现在需要检查用户是否具有某些权限。

As I see it now I have to implement a new class which implements CanActivate for every single permission. 正如我现在所看到的,我必须实现一个新的类,它为每个权限实现CanActivate。 Right now this would mean I'd have 7. We're however in an early stage of this exact project and Without too much thought I could improve this to 11. 现在这意味着我将拥有7.然而,我们处于这个确切项目的早期阶段并且没有太多想到我可以将其提高到11。

What I can see before me is an implementation which will only cost me about 3 - 5 lines per such canActivate implementation. 我在我之前看到的是一个实现,每个canActivate实现只需要花费大约3-5行。 However I would feel more helped by an implementation where I could provide properties or parameters. 但是,通过我可以提供属性或参数的实现,我会感觉更有帮助。

Not to think of the situation I'd have to implement classes like: 不要想到我必须实现以下类的情况:

CanActivateIfUserHasPermissionsViewContentAndViewUsers or even longer. CanActivateIfUserHasPermissionsViewContentAndViewUsers甚至更长。

Note in my situation permissions are basically multiple actions. 注意在我的情况下权限基本上是多个动作。 Like View all Content elements, Or edit all of them etc. 比如查看所有内容元素,或者编辑所有内容元素等。

So I didn't find a way to implement my CanActivate with params. 所以我找不到用params实现CanActivate的方法。

I did however find a workaround which seems fine for me now. 然而,我找到了一个对我来说似乎很好的解决方法。 I have a service in which I can load my routes on Module construct. 我有一个服务,我可以在Module构造上加载我的路由。 (I just add it in the constructor of the module). (我只是将它添加到模块的构造函数中)。

My Routes now contain data { permissions: [My values here] }. 我的路线现在包含数据{权限:[我在这里的值]}。 Which are checked in the canActive hook, since the canActivate implementation also uses the same service. 在canActive钩子中检查了哪些,因为canActivate实现也使用相同的服务。

My solution is based on my discussion on this other question: Angular2 RC5 Cross-Module Provider / Scanning 我的解决方案基于我对另一个问题的讨论: Angular2 RC5跨模块提供程序/扫描

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM