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.

June 26, 2023 angularangular-15

You can view the source code for this project by following this link: GitHub

Demo

Creating AuthService

Let’s create an AuthService with a method to check if a user has required permission.

1
import { Injectable } from "@angular/core";
2
3
export type Permission = "reading" | "writing";
4
5
@Injectable({ provideIn: "root" })
6
export class AuthService {
7
private userPermissions: Permission[] = [];
8
9
hasPermission(permission: Permission): boolean {
10
return this.userPermissions.includes(permission);
11
}
12
}

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.

1
import { Injectable } from "@angular/core";
2
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from "@angular/router";
3
import { AuthService } from "./auth.service";
4
5
// The old way to create a guard using classes
6
@Injectable({ provideIn: "root" })
7
export class PermissionGuard implements CanActivate {
8
constructor(private authService: AuthService) {}
9
10
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
11
// `requiredPermission` has type `any`
12
const requiredPermission = route.data.requiredPermission;
13
return this.authService.hasPermission(requiredPermission);
14
}
15
}
16
17
// example routes
18
19
const routes: Routes = [
20
{
21
path: "protected",
22
component: ProtectedComponent,
23
canActivate: [PermissionGuard],
24
data: { requiredPermission: "rading" }, // typo and no error
25
},
26
// Other routes...
27
];

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.

1
// Check if user is admin
2
const route = {
3
path: "protected",
4
canActivate: [() => inject(AuthService).hasPermission("rading")], // typo and error!
5
};

Moreover, you can create a factory function to remove the boilerplate and keep the code to a minimum.

1
// Factory to check if user has required permission
2
export function provideGuardForPermission(permission: Permission) {
3
return () => inject(AuthService).hasPermission(permission);
4
}

After that, you can use the created function in places where it is required.

1
export const ROOT_ROUTES: Routes = [
2
{
3
path: "a",
4
loadComponent: () => import("./page-a.component"),
5
// Examples of usage provideGuardForPermission factory
6
canActivate: [provideGuardForPermission("writing")],
7
},
8
{
9
path: "b",
10
loadComponent: () => import("./page-b.component"),
11
canMatch: [provideGuardForPermission("reading")],
12
},
13
{
14
path: "b",
15
loadComponent: () => import("./403.component"),
16
},
17
];

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.

Leave a comment