Functional router guards – the new way of creating guards in Angular
Before Angular v15 we had to create guards as a class which was a big boilerplate even though we had simple logic.
Additionally, passing parameters to guard via data was not strict, so we were able to have a typo and the compiler did not throw an error.
Everything changed when Angular v15 comes and provides functional router guards.
Let’s create an AuthService with a method to check if a user has required permission.
The old way to create a guard (classes)
In the old way, guards are implemented as classes.
There is no possibility to pass additional information to canActivate function.
To do it you had to get data from route and define this in route configuration while losing strict typing.
The new way to create guard (functions)
Angular v15 provides a method inject and possibility to define a guard as a function.
That means you do not have to create a class, you just need one function.
Moreover, you can create a factory function to remove the boilerplate and keep the code to a minimum.
After that, you can use the created function in places where it is required.
Do you like the content?
Your support helps me continue my work. Please consider making a donation.
Donations are accepted through PayPal or Stripe. You do not need a account to donate. All major credit cards are
accepted.