Sub topic 3
Writing functional guards with inject()
This chapter assumes you know TypeScript, Angular services and dependency injection, the Routes array, and basic RxJS. It covers how to write a guard as a plain function and how to get services into it with inject(). The chapters before and after this one cover the return values and each guard type in detail.
A guard is a function
Since Angular 15.2, a guard is an ordinary function. You don't need a class that implements CanActivate. The router imports a type for each guard kind, such as CanActivateFn, and your function must match it.
A CanActivateFn receives two arguments:
route: anActivatedRouteSnapshotfor the route being activated. It holds params, query params, anddata.state: aRouterStateSnapshot. Itsurlproperty is the full URL the user is trying to reach.
The function returns a value that tells the router what to do. The return values are covered in the next chapter. This chapter's examples return true, false, or a UrlTree.
Functions don't have constructors, so a guard can't ask for services as constructor parameters. It calls inject() instead.
Getting services with inject()
inject() is a function from @angular/core. It returns an instance from the current dependency injector, but only inside an injection context. The router runs your guard inside one, so calling inject() in the guard body works.
Here is a small service for the examples:
import { Injectable, signal } from '@angular/core';
interface User {
name: string;
roles: string[];
}
@Injectable({ providedIn: 'root' })
export class AuthService {
private readonly user = signal<User | null>(null);
isLoggedIn(): boolean {
return this.user() !== null;
}
hasRole(role: string): boolean {
return this.user()?.roles.includes(role) ?? false;
}
login(user: User): void {
this.user.set(user);
}
logout(): void {
this.user.set(null);
}
}And a guard that uses it:
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 },
});
};Both inject() calls come first, then the logic runs. Keeping them at the top of the function is a good habit, and the next section explains why it matters.
You attach the guard by passing the function itself, without calling it:
{ path: 'account', canActivate: [authGuard], component: AccountComponent }If you write canActivate: [authGuard()], you call the guard at configuration time, outside any injection context. That fails or gives the wrong value.
Where the injection context ends
An injection context exists only while the router is synchronously running your function. Once your code reaches an await, a .then() callback, or an RxJS operator callback, the context is gone. A later inject() call throws a runtime error, NG0203 ("inject() must be called from an injection context").
This guard fails:
import { inject } from '@angular/core';
import { CanActivateFn } from '@angular/router';
import { AuthService } from './auth.service';
export const brokenGuard: CanActivateFn = async () => {
await fetch('/api/ping');
const auth = inject(AuthService); // throws NG0203: the context is gone
return auth.isLoggedIn();
};The fix is to resolve every dependency before the first asynchronous step:
import { inject } from '@angular/core';
import { CanActivateFn } from '@angular/router';
import { AuthService } from './auth.service';
export const workingGuard: CanActivateFn = async () => {
const auth = inject(AuthService);
await fetch('/api/ping');
return auth.isLoggedIn();
};Helper functions called from a guard
A helper function can call inject() too, as long as the guard calls the helper synchronously. The helper runs in the same injection context.
import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { AuthService } from './auth.service';
function redirectToLogin(returnUrl: string) {
return inject(Router).createUrlTree(['/login'], { queryParams: { returnUrl } });
}
export const memberGuard: CanActivateFn = (route, state) =>
inject(AuthService).isLoggedIn() || redirectToLogin(state.url);This keeps repeated redirect logic in one place. The cost is that a reader can't see from the helper's signature that it needs an injection context. Name such helpers clearly and comment on the requirement.
Guards that take parameters
A guard function has a fixed signature, so you can't pass your own arguments to it from the route config. To parameterize a guard, write a factory: a function that takes your arguments and returns a guard.
import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { AuthService } from './auth.service';
export function requireRole(role: string): CanActivateFn {
return () => {
const auth = inject(AuthService);
const router = inject(Router);
return auth.hasRole(role) || router.parseUrl('/forbidden');
};
}Here you do call the factory in the route config, because it returns the guard:
{
path: 'editor',
canActivate: [authGuard, requireRole('editor')],
loadComponent: () => import('./editor.component').then(m => m.EditorComponent),
}The inner arrow function is the real guard. The router calls it in an injection context, so inject() works there. The outer factory runs earlier, when the routes array is built, so don't call inject() in the outer function.
An alternative is to put static values in the route's data property and read them from route.data. A factory gives you type-checked arguments. data keeps the guard a single shared function. Choose a factory when the parameter is fixed per route and data when other code, such as a menu, also needs to read it.
Guards can be reused across guard types
The type aliases differ in their parameters, but the shapes overlap. A function that ignores its arguments, like () => inject(AuthService).isLoggedIn(), is assignable to CanActivateFn, CanActivateChildFn, and CanMatchFn. For example:
import { inject } from '@angular/core';
import { CanActivateChildFn, CanActivateFn, CanMatchFn } from '@angular/router';
import { AuthService } from './auth.service';
const isLoggedIn = () => inject(AuthService).isLoggedIn();
export const authActivate: CanActivateFn = isLoggedIn;
export const authActivateChild: CanActivateChildFn = isLoggedIn;
export const authMatch: CanMatchFn = isLoggedIn;Reuse is safe only when the guard doesn't read route or state. The route argument means something different for canMatch than for canActivate, so a guard that reads it should be typed for one kind.
Common mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Calling `inject()` after `await` or inside a callback | NG0203 at navigation time | Resolve all dependencies at the top of the function |
| Writing `canActivate: [authGuard()]` for a plain guard | Type error, or NG0203 at startup | Pass `authGuard` without parentheses |
| Calling `inject()` in the outer function of a factory | NG0203 when routes are created | Call `inject()` inside the returned guard |
| Reading state that isn't loaded yet, such as a user fetched asynchronously | The guard denies access on first load | Return an `Observable` or `Promise` that waits for the data |
| Throwing an error from a guard | The navigation fails with an error | Return `false` or a `UrlTree` for expected denials |
Why functions over classes
Functional guards are shorter, and you can create them inline for simple cases. They tree-shake well because they are plain exports. They also compose: you can wrap them in factories and combine them in a helper.
Classes are not forbidden. Older guard classes still work in many versions, but the class-based guard interfaces are deprecated. A later chapter on legacy guards shows how to recognize and migrate them. If you need a class, you can adapt it with inject(MyGuardClass).canActivate(route, state) inside a function.
Exercise
A teammate writes this guard. It compiles, but navigation fails with NG0203. What is wrong, and how do you fix it? export const profileGuard: CanActivateFn = () => { return inject(UserApi).load().pipe( map(user => user !== null || inject(Router).parseUrl('/login')), ); };
Show answer
The second inject() call is inside the map() callback, which runs after the HTTP request completes, when the injection context has ended. Call inject(Router) at the top of the guard and use the stored reference in the callback: const router = inject(Router); const api = inject(UserApi); return api.load().pipe(map(user => user !== null || router.parseUrl('/login')));
Exercise
You need the same role check on five routes, each requiring a different role. Which pattern fits, and where does inject() go?
Show answer
Write a factory such as requireRole(role: string): CanActivateFn and call it in each route, for example canActivate: [requireRole('editor')]. The inject() calls go inside the returned guard function, not in the outer factory, because only the inner function runs in an injection context.