Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 Router CanActivate, with Parameters?

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.

like image 310
Mathijs Segers Avatar asked Nov 09 '22 10:11

Mathijs Segers


1 Answers

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

like image 78
Mathijs Segers Avatar answered Nov 15 '22 06:11

Mathijs Segers