So, you write dozens and dozens of routes, add parameters, hack them with data revolvers, and now, anyone can access any page, but you really don’t want it, you want to provide access by permission.

Your first step will be to create CanActivateGuard.

But how the guard can know which permission is required to which component.

Suggested 2 ways:

Route data:

For any route you we will define data object contains required permission.

Route config will look like this:

And the guard will look like:

2. Component decorator

Route guard will be defined only once. in the root route, using canActivateChild to make it relevant also for child routes.

Then, any route component will use special decorator that we will create that define the required permission.

And Guard will read the component decorator, take it’s defined permissions and call the security service (or any other logic) to check if the user can access to that page.

Route Config:

Decorator:

This is the decorator function, that adds to the component a field contains the required permission. (this isn’t added to the component instance, just on the component constructor function)

Here is how we use the decorator on some component:

Guard:

What is better?

In the second option, we can define the guard only once, for the root route, and this affects any child root that will be added.

No one will need to remember this guard anymore, and in a large application, where developers add a route any day it’s very easy to forget the need to add also the guard and its data to the config.

In this approach you just add decorator and you are done, no need touch in the route config.