canActivate is the route-guard entry point that decides whether navigation may continue or returns an UrlTree redirect. Older Angular guards implement it on a state-free class; the modern approach defines a CanActivateFn and uses inject directly, removing the class when dependency injection is the only reason it exists. section 3.3.1
Protecting an employees route
A functional authGuard injects AuthService and Router, maps isAuth$ to either true or router.createUrlTree(['/login']), and is registered with canActivate: [authGuard]. This restricts HRMS business pages to authenticated users while redirecting others. section 3.3.1
Listing 3.9 Functional route guard
import { inject } from '@angular/core';
import { CanActivateFn, Router, } from '@angular/router';
import { map } from 'rxjs/operators';
import { AuthService } from 'src/app/services/auth.service';
export const authGuard: CanActivateFn = () => { #1
const router = inject(Router); #2
const authService = inject(AuthService);
return authService.isAuth$.pipe( #3
map((isAuth) => isAuth || router.createUrlTree(['/login'])), #4
);
}
Shows the functional CanActivateFn implementation, dependency injection, observable decision, and login redirect. section 3.3.1
For incremental migration:
- Register an existing class-based guard with mapToCanActivate([AuthGuard]) while converting guards individually. section 3.3.4
- Replace the class with a CanActivateFn when its main purpose is dependency injection and a single canActivate decision. section 3.3.1
