Sub topic 3
Writing functional guards with inject()
This chapter assumes you know TypeScript, Angular services and dependency injection, and the basics of the Routes array. You should also be comfortable reading an RxJS Observable or a Promise.
From classes to functions
A functional guard is a plain function that the router calls during navigation. It replaces the older class-based guard that implemented an interface such as CanActivate. The router passes the function information about the navigation, and the function returns a decision.
Each guard type has a matching function type, such as CanActivateFn, CanDeactivateFn and CanMatchFn. These types describe the parameters the router supplies and the values the function may return.
Using inject() to get services
A function has no constructor, so it cannot receive services as constructor parameters. Angular provides the inject() function instead. The router runs your guard inside an injection context, which is the state in which inject() is allowed to work.
import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { AuthService } from './auth.service';
export const authGuard: CanActivateFn = (route, state) => {
const auth = inject(AuthService);
const router = inject(Router);
if (auth.isLoggedIn()) {
return true;
}
return router.createUrlTree(['/login'], {
queryParams: { returnUrl: state.url },
});
};The function does four things:
- It calls
inject(AuthService)andinject(Router)at the top of the body. - It asks the service whether the user is logged in.
- If so, it returns
trueand the navigation continues. - Otherwise it returns a
UrlTreethat sends the user to/loginand keeps the requested URL in thereturnUrlquery parameter.
The two parameters are route, an ActivatedRouteSnapshot for the route being activated, and state, a RouterStateSnapshot that holds the full target URL in state.url. You can leave out parameters you do not use.
Attaching a guard to a route
You register a guard by putting the function itself, not a call to it, in the matching array on the route.
import { Routes } from '@angular/router';
import { authGuard } from './auth.guard';
export const routes: Routes = [
{
path: 'account',
canActivate: [authGuard],
loadComponent: () => import('./account.component').then(m => m.AccountComponent),
},
];Write authGuard, not authGuard(). The router calls the function for you at the right moment.
Guards compose well
Because guards are ordinary functions, you can build them with a factory. A factory is a function that returns a guard, which lets you configure it for each route.
import { inject } from '@angular/core';
import { CanActivateFn } from '@angular/router';
import { AuthService } from './auth.service';
export const hasRole = (role: string): CanActivateFn => () =>
inject(AuthService).hasRole(role);On a route you would write canActivate: [hasRole('editor')]. Here the call is intended, because hasRole returns the guard.
Common mistakes
- Calling
inject()after anawait. - Writing
canActivate: [authGuard()]for a guard that is not a factory. - Using
inject()in a helper function that the router does not call from within the guard's own synchronous body. Pass the services in as arguments instead.
Exercise
Why does the guard in this chapter call inject(Router) at the top of the function and not inside a .then() callback after an asynchronous call?
Show answer
inject() works only in an injection context, which exists while the router synchronously runs the guard function. Inside a .then() callback the context is gone, so inject() would throw. Calling it at the top keeps it inside the context, and the resulting service references can be used later in callbacks.
Exercise
A route needs a guard that only lets users with the role editor through. How would you avoid writing a separate guard function for every role?
Show answer
Write a factory such as hasRole(role: string): CanActivateFn that returns a guard calling inject(AuthService).hasRole(role). Then register it with canActivate: [hasRole('editor')].