Sub topic 17
Recognizing legacy class-based guards
This chapter assumes you can read functional guards and know Angular dependency injection. Older Angular code uses a different style, and you will meet it in existing projects. Here you learn to recognize it and convert it.
What the old style looks like
Before Angular 14.2, a guard was an injectable class that implemented an interface such as CanActivate. The router called its canActivate method.
import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, 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 {
return this.auth.isLoggedIn()
? true
: this.router.createUrlTree(['/login'], { queryParams: { returnUrl: state.url } });
}
}The route configuration refers to the class itself:
{ path: 'admin', component: AdminComponent, canActivate: [AuthGuard] }The telltale signs are @Injectable, implements CanActivate (or CanDeactivate, CanMatch, Resolve), constructor injection, and a class name in the route array.
Why this style is deprecated
The class interfaces (CanActivate, CanActivateChild, CanDeactivate, CanMatch, Resolve) are deprecated. Class-based guards still run in versions that keep them, but new code should use functions. Functions are shorter, need no registration as a provider, and can be composed or reused inline. Check your Angular version's release notes before relying on the old interfaces, because deprecated APIs can be removed.
Mapping old to new
| Legacy class | Functional equivalent |
|---|---|
| `implements CanActivate` | `CanActivateFn` |
| `implements CanActivateChild` | `CanActivateChildFn` |
| `implements CanDeactivate<T>` | `CanDeactivateFn<T>` |
| `implements CanMatch` | `CanMatchFn` |
| `implements Resolve<T>` | `ResolveFn<T>` |
The conversion is mechanical: replace constructor parameters with inject() calls and turn the method body into the function body.
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 } });
};Migrating without rewriting everything
If a class guard is large or widely used, you can bridge it instead of rewriting it. Inside a functional guard, call inject() on the class and delegate to its method:
import { inject } from '@angular/core';
import { CanActivateFn } from '@angular/router';
import { AuthGuard } from './auth.guard';
export const authGuardFn: CanActivateFn = (route, state) =>
inject(AuthGuard).canActivate(route, state);This works because the class is providedIn: 'root'. Use it as a temporary step and remove the class later.
Common mistakes during migration
- Calling
inject()inside a callback such assubscribeorsetTimeout. It only works in the synchronous injection context at the top of the function, so call it first. - Forgetting that
thisno longer exists. Move any class state into an injected service. - Leaving the old class registered in the route array after writing the function version.
Exercise
A route has canDeactivate: [UnsavedGuard], where UnsavedGuard is a class with implements CanDeactivate<FormComponent> and a method canDeactivate(component). Which type do you use for the functional version, and where does the component argument go?
Show answer
Use CanDeactivateFn<FormComponent>. The component becomes the first parameter of the function: (component) => .... Any services the class received in its constructor are obtained with inject() at the top of the function.