Sub topic 11
Protecting Routes with Functional Guards
This chapter assumes you know how to define routes, inject services with inject(), and navigate with Router. A guard is a function the router calls during navigation. It decides whether the navigation continues, stops, or redirects somewhere else.
The working model
A guard can return true to allow navigation or false to cancel it. It can also return a UrlTree, which cancels the current navigation and starts a new one to that URL. The router also accepts an Observable or Promise of any of these values and waits for it to settle before continuing. Guards run inside an injection context, so you can call inject() directly in the function body.
The three guards you will use most
| Guard type | When it runs | Typical use |
|---|---|---|
| `CanActivateFn` | After the route matches, before it activates | Block signed-out users |
| `CanMatchFn` | While the router matches the URL to a route | Skip a route, or stop a lazy bundle from downloading |
| `CanDeactivateFn<T>` | When the user leaves an active route | Warn about unsaved changes |
CanActivateFn
import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { AuthService } from './auth.service';
export const authGuard: CanActivateFn = () => {
const auth = inject(AuthService);
const router = inject(Router);
return auth.isLoggedIn() ? true : router.createUrlTree(['/login']);
};
// Usage in a route definition:
// { path: 'dashboard', component: DashboardComponent, canActivate: [authGuard] }Returning a UrlTree is better than calling router.navigate() inside the guard and then returning false. With a UrlTree, the router handles the redirect as part of the same navigation, so you avoid races between two navigations.
CanMatchFn
A CanMatchFn guard that returns false makes the router act as if the route does not exist, and it moves on to the next route in the list. On a loadChildren or loadComponent route, this also stops the lazy code from being downloaded.
import { inject } from '@angular/core';
import { CanMatchFn, Routes } from '@angular/router';
import { AuthService } from './auth.service';
export const adminMatch: CanMatchFn = () => inject(AuthService).isAdmin();
export const routes: Routes = [
{
path: 'admin',
canMatch: [adminMatch],
loadChildren: () => import('./admin/admin.routes').then(m => m.ADMIN_ROUTES)
}
];CanDeactivateFn
A CanDeactivateFn guard receives the component instance that is currently active, so it can read that component's state.
import { CanDeactivateFn } from '@angular/router';
export interface HasUnsavedChanges {
hasUnsavedChanges(): boolean;
}
export const unsavedChangesGuard: CanDeactivateFn<HasUnsavedChanges> = (component) =>
component.hasUnsavedChanges()
? confirm('You have unsaved changes. Leave anyway?')
: true;
// { path: 'edit/:id', component: EditComponent, canDeactivate: [unsavedChangesGuard] }Common errors
- Calling
inject()in a callback.inject()only works while the guard function runs synchronously. Inject your services at the top of the guard, then use them insidepipe()orthen()callbacks. - Treating guards as security. Guards only control what the client shows. Your server must still check authorization on every API call.
- Using
canActivateto protect lazy code. WithcanActivate, the lazy bundle downloads before the guard rejects the navigation. UsecanMatchif users should never receive that code. - Observables that never complete. The router waits for the first emitted value. A stream that never emits leaves navigation hanging, so add
take(1)or make sure the source emits.
Exercise
A route uses loadChildren for a reporting module that only managers should download. Which guard type should you use, and what should it return for non-managers who should land on /home?
Show answer
Use a CanMatchFn on the route through canMatch, so the bundle is never fetched for non-managers. Have it return inject(Router).createUrlTree(['/home']) instead of false, so the router redirects them in the same navigation.
Exercise
Why does this guard throw an error? export const g: CanActivateFn = () => of(null).pipe(map(() => inject(AuthService).isLoggedIn()));
Show answer
inject() runs inside the map callback, which executes outside the guard's synchronous injection context. Call const auth = inject(AuthService) at the top of the guard, then use auth inside map.