Sub topic 5
Protecting a route with canActivate
This chapter assumes you know TypeScript, Angular services, the Routes array, and how inject() works. You should also be comfortable with Observables and Promises.
What canActivate does
canActivate runs when the router is about to activate a route. If the guard says no, the navigation is cancelled and the current page stays in place. You use it for rules such as "only logged-in users may see this page".
A guard is attached to a route in the canActivate array. The router runs every guard in that array.
A functional guard
A functional guard is a plain function of type CanActivateFn. It receives the ActivatedRouteSnapshot for the route and the RouterStateSnapshot for the target URL. Call inject() at the top of the function to get services.
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 },
});
};The guard returns true to allow the navigation. Otherwise it returns a UrlTree, which tells the router to cancel this navigation and go to /login. The state.url value is the URL the user asked for, so the login page can send them back after sign-in.
Call inject() synchronously, before any await or .then(). Outside that synchronous window there is no injection context, and Angular throws an error.
Attaching the guard to a route
import { Routes } from '@angular/router';
import { authGuard } from './auth.guard';
import { productResolver } from './product.resolver';
export const routes: Routes = [
{ path: 'login', loadComponent: () => import('./login.component').then(m => m.LoginComponent) },
{
path: 'products/:id',
canActivate: [authGuard],
resolve: { product: productResolver },
loadComponent: () => import('./product-detail.component').then(m => m.ProductDetailComponent),
},
];Here canActivate: [authGuard] protects products/:id. The resolve entry loads data for the route. Resolvers are covered in a later chapter, and for now it is enough to know that guards run before them.
Common errors
- Forgetting to return on every path. A guard that returns nothing in some branch gives
undefined, and the navigation fails. - Returning
falsewhen you meant to redirect.falsecancels the navigation and leaves the user with no feedback. Return aUrlTreewhen they need to go somewhere. - Calling
router.navigate()inside the guard. This starts a second navigation while the first is still running. Return aUrlTreeinstead. - Calling
inject()after anawait. Get all your services first.
Exercise
A guard contains if (!auth.isLoggedIn()) { router.navigate(['/login']); return false; }. What is the problem, and how would you fix it?
Show answer
Calling router.navigate() inside the guard starts a second navigation while the first is still in progress, which can cause races and confusing history entries. Replace it with return router.createUrlTree(['/login']), so the router cancels the current navigation and redirects in one step.