Angular2 Router CanActivate, with Parameters?

老子叫甜甜 提交于 2020-01-03 13:01:18

问题


i've seen some issues on this specific issue.

I'm lately only working on angular2 projects. 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).

Currently we can conform to the CanActivate Class/Interface row w/e we can call it.

Right now I would like to be able to provide Permissions (which I've slapped into an Enum) to such CanActivate classes. 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.

As I see it now I have to implement a new class which implements CanActivate for every single permission. 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.

What I can see before me is an implementation which will only cost me about 3 - 5 lines per such canActivate implementation. 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.

Note in my situation permissions are basically multiple actions. Like View all Content elements, Or edit all of them etc.


回答1:


So I didn't find a way to implement my CanActivate with params.

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. (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.

My solution is based on my discussion on this other question: Angular2 RC5 Cross-Module Provider / Scanning



来源:https://stackoverflow.com/questions/39020453/angular2-router-canactivate-with-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!