Sub topic 17
Recognizing legacy class-based guards
This chapter assumes you can write the functional guards and resolvers from the earlier chapters, and that you know @Injectable, constructor injection, and the Routes array. Here you will learn to read the older class-based style, map each part to its functional equivalent, and migrate code step by step.
Why you still meet class-based guards
Before Angular 14.2, a guard was a class. It implemented an interface such as CanActivate and was registered by class name in the route configuration. Functional guards arrived in 14.2. Angular 15.2 marked the class-based interfaces (CanActivate, CanActivateChild, CanDeactivate, CanMatch and Resolve) as deprecated. The older CanLoad interface was deprecated earlier, and canMatch replaces it.
Deprecated does not mean broken. Many tutorials, Stack Overflow answers and large codebases still use classes, and the router still runs them. You need to read them fluently and know how to convert them.
Anatomy of a class-based guard
This is a typical legacy guard:
import { Injectable } from '@angular/core';
import {
ActivatedRouteSnapshot,
CanActivate,
Router,
RouterStateSnapshot,
UrlTree,
} from '@angular/router';
import { AuthService } from './auth.service';
@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
constructor(
private auth: AuthService,
private router: Router,
) {}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot,
): boolean | UrlTree {
if (this.auth.isLoggedIn()) {
return true;
}
return this.router.createUrlTree(['/login'], {
queryParams: { returnUrl: state.url },
});
}
}Four features identify the legacy style:
- The class has an
@Injectabledecorator. - It has an
implementsclause naming a guard interface. - Dependencies arrive through the constructor, not through
inject(). - The logic lives in a method whose name matches the guard type, such as
canActivate.
The route configuration passes the class itself, not a function:
import { Routes } from '@angular/router';
import { AuthGuard } from './auth.guard';
import { ProductResolver } from './product.resolver';
export const routes: Routes = [
{
path: 'products/:id',
canActivate: [AuthGuard],
resolve: { product: ProductResolver },
loadComponent: () =>
import('./product-detail.component').then(m => m.ProductDetailComponent),
},
];The router asks the dependency injector for an instance of AuthGuard and calls its canActivate method. The return values mean exactly what they mean for functional guards: boolean, UrlTree, or a Promise or Observable of those.
The legacy interfaces and their functional equivalents
Each interface maps one-to-one onto a function type and a router helper.
| Legacy interface | Method to implement | Functional type | Bridge helper |
|---|---|---|---|
| `CanActivate` | `canActivate(route, state)` | `CanActivateFn` | `mapToCanActivate` |
| `CanActivateChild` | `canActivateChild(childRoute, state)` | `CanActivateChildFn` | `mapToCanActivateChild` |
| `CanDeactivate<T>` | `canDeactivate(component, currentRoute, currentState, nextState)` | `CanDeactivateFn<T>` | `mapToCanDeactivate` |
| `CanMatch` | `canMatch(route, segments)` | `CanMatchFn` | `mapToCanMatch` |
| `Resolve<T>` | `resolve(route, state)` | `ResolveFn<T>` | `mapToResolve` |
One class can implement several interfaces. A single AuthGuard might provide both canActivate and canActivateChild. Functional guards are one function per guard type, so a combined class becomes several small functions that can share a helper.
Legacy resolvers
A class-based resolver follows the same pattern with Resolve<T>:
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, Resolve } from '@angular/router';
import { Observable } from 'rxjs';
import { Product, ProductService } from './product.service';
@Injectable({ providedIn: 'root' })
export class ProductResolver implements Resolve<Product> {
constructor(private products: ProductService) {}
resolve(route: ActivatedRouteSnapshot): Observable<Product> {
return this.products.getById(route.paramMap.get('id')!);
}
}The resolve key in the route works as before, so the component still reads the data as product. Only the packaging differs.
Migrating to functional guards
Converting a class is mostly mechanical:
- Replace the class with an exported
constof the matching function type (for exampleCanActivateFn). - Replace each constructor parameter with an
inject()call at the top of the function body. - Replace
this.authandthis.routerwith the local variables. - In the route, replace the class name with the function name.
- Delete the
@Injectabledecorator and theimplementsclause.
Applied to the AuthGuard above, the result is the guard you already know:
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);
return auth.isLoggedIn()
? true
: router.createUrlTree(['/login'], { queryParams: { returnUrl: state.url } });
};The behavior is identical. The function is shorter, and the route array now holds authGuard, not AuthGuard.
Migrating gradually with the bridge helpers
A large application may have dozens of guard classes. You do not have to convert them in one pass. The mapTo... helpers wrap existing classes so that the route configuration speaks the functional language:
import { Routes, mapToCanActivate, mapToResolve } from '@angular/router';
import { AuthGuard } from './auth.guard';
import { ProductResolver } from './product.resolver';
export const routes: Routes = [
{
path: 'products/:id',
canActivate: mapToCanActivate([AuthGuard]),
resolve: { product: mapToResolve(ProductResolver) },
loadComponent: () =>
import('./product-detail.component').then(m => m.ProductDetailComponent),
},
];Each helper takes the class (or an array of classes, except mapToResolve, which takes one) and returns functions that look the instance up with inject() and call the right method. This lets you remove the deprecated class usage from route configuration first, and rewrite the class bodies later.
You can also call a class from inside a new function:
export const legacyBridgeGuard: CanActivateFn = (route, state) =>
inject(AuthGuard).canActivate(route, state);Use this only as a stepping stone, because the deprecated interface is still in your code.
Common errors during migration
- Leaving the class name in the route after converting. The function is named
authGuardand the class wasAuthGuard. A stale import produces a type error that is easy to fix, but only if the old file was actually deleted or changed. - Calling
inject()outside an injection context. In a functional guard, callinject()at the top level of the function, before anyawaitor callback. After an asynchronous gap the injection context is gone and Angular throws. - Missing
providedIn: 'root'on a class guard. The router resolves the class from the injector. If the class is not provided anywhere, you get aNullInjectorError. Functional guards avoid this because the function needs no provider. - Forgetting that tests change shape. A class guard is tested by calling
TestBed.inject(AuthGuard)and then invoking its method. A functional guard is tested withTestBed.runInInjectionContext, as shown in the testing chapter. Update the tests in the same commit as the guard. - Assuming deprecated means removed. Code that still uses classes keeps working. Migrate on a schedule, not in a panic, and check the deprecation notes of your Angular version before upgrading.
Exercise
A route has canActivate: [AdminGuard] where AdminGuard is a class that implements both CanActivate and CanActivateChild and injects AuthService in its constructor. Describe two ways to modernize it, and name one advantage of each.
Show answer
(1) Quick bridge: change the route to canActivate: mapToCanActivate([AdminGuard]) and canActivateChild: mapToCanActivateChild([AdminGuard]). The advantage is that the class body stays untouched, so the change is small and low risk. (2) Full rewrite: create one CanActivateFn and one CanActivateChildFn (the child function can simply call a shared helper or return the same check), use inject(AuthService) inside them, and list the functions in the route. The advantage is that no deprecated interface remains, no @Injectable class is needed, and the guard is tested with runInInjectionContext.