Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 74 ยท Routing

Guards, Resolvers and Router Events

Protect routes with functional guards (canActivate, canMatch, canDeactivate), preload page data with resolvers, redirect with UrlTree and react to router events.

Matching a URL to a component is only half of what a router does. Before the page appears you often need to ask questions: Is this user signed in? May they open this admin area? Are there unsaved changes on the page they're leaving? Does the data this page needs exist? Angular answers these with guards (functions that allow, block or redirect a navigation) and resolvers (functions that fetch data before the route activates). The router also announces every step as an event, which you can use for loading indicators and analytics.

Everything here builds on Routing Basics, parameters and navigation and lazy routes.

The real Angular code is read-only, because the site can't run the Angular compiler. The runnable examples are stand-ins: a guard pipeline that allows, blocks or redirects, and a mini router that resolves data and emits events. They model the decisions, not Angular's implementation.

What happens during a navigation

Every navigation goes through the same stages. Guards run first and can stop or redirect it, resolvers run next and delay it until data is ready, and only then are components created and the URL updated.

flowchart LR
  A["NavigationStart"] --> B["canMatch<br/>(is this route even available?)"]
  B --> C["canDeactivate<br/>(may we leave the old page?)"]
  C --> D["canActivate and<br/>canActivateChild"]
  D --> E["resolve<br/>(fetch data)"]
  E --> F["Activate components<br/>update the URL"]
  F --> G["NavigationEnd"]

A guard that returns false stops the pipeline and produces a NavigationCancel event; an error produces NavigationError.

Functional guards

Modern Angular guards are plain functions. They run in an injection context, so you can call inject() inside them to get services. The function's type tells the router when to run it:

TypeScript
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.isSignedIn()) {
    return true;
  }
  // Redirect instead of just blocking, and remember where the user wanted to go
  return router.createUrlTree(['/login'], { queryParams: { returnUrl: state.url } });
};

A guard may return:

  • true: allow the navigation.
  • false: cancel it; the user stays on the current page.
  • a UrlTree: cancel this navigation and start a new one to that URL (built with router.createUrlTree([...]) or router.parseUrl('/login')). Prefer this over calling router.navigate() inside the guard, because the router handles the replacement cleanly.
  • a Promise or Observable of any of the above, for asynchronous checks such as asking a server.

You attach guards to routes as arrays:

TypeScript
export const routes: Routes = [
  { path: 'login', component: LoginComponent },
  { path: 'account', component: AccountComponent, canActivate: [authGuard] },
  {
    path: 'admin',
    canActivate: [authGuard, roleGuard('admin')],
    loadChildren: () => import('./admin/admin.routes').then((m) => m.ADMIN_ROUTES),
  },
];

A guard that needs a parameter is a function that returns a guard, as roleGuard('admin') does:

TypeScript
export function roleGuard(role: string): CanActivateFn {
  return () => {
    const auth = inject(AuthService);
    return auth.hasRole(role) || inject(Router).createUrlTree(['/forbidden']);
  };
}

Guards improve the user experience; they are not security. All the code of an Angular app is delivered to the browser, and a determined user can bypass any client-side check. Your server must enforce permissions on every request. Use guards to avoid showing pages and fetching data a user can't use.

The four kinds of guard

Guard Runs when Typical use
canMatch While matching, before the route is even considered a candidate Hide a lazy route entirely, or pick between two routes with the same path (for example by feature flag) without downloading the chunk
canActivate Before a route is activated Authentication, authorization
canActivateChild Before any child of a route is activated One check for a whole group of children
canDeactivate Before leaving the current route Warn about unsaved changes

canMatch supersedes the older canLoad. Older class-based guards (a class with a canActivate() method) still exist but are deprecated in favor of functions.

A typical canDeactivate guard receives the component being left, so it can ask it directly:

TypeScript
export interface HasUnsavedChanges {
  hasUnsavedChanges(): boolean;
}

export const unsavedChangesGuard: CanDeactivateFn<HasUnsavedChanges> = (component) =>
  !component.hasUnsavedChanges() || confirm('Discard your changes?');

If several guards sit in the same array, any one that returns false or a UrlTree stops the navigation. Don't depend on side effects happening in a particular order between guards; keep each guard a pure question.

A runnable guard pipeline

This stand-in follows the rules above: guards run in order, the first one that doesn't return true stops the pipeline, a redirect starts a new navigation (with a limit, because two guards redirecting to each other would loop forever), and guards may be asynchronous.

TypeScript Stand-in: a guard pipeline with redirects

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Notice how the guest's redirect carries a returnUrl, so a login page could send them back after signing in. The /loop route shows the danger of a redirect that points at itself; make sure your redirect targets are always routes that allow the user through.

Resolvers

A resolver is a function that fetches data before the route activates, so the component starts with its data already in hand instead of showing an empty page and a spinner:

TypeScript
import { inject } from '@angular/core';
import { ResolveFn } from '@angular/router';
import { catchError, of } from 'rxjs';
import { Course, CourseService } from './course.service';

export const courseResolver: ResolveFn<Course | null> = (route) => {
  const id = route.paramMap.get('id') ?? '';
  return inject(CourseService).load(id).pipe(catchError(() => of(null)));
};

export const routes: Routes = [
  {
    path: 'courses/:id',
    component: CourseDetailComponent,
    resolve: { course: courseResolver },
  },
];

The resolved value appears under the key you chose. With withComponentInputBinding() the component declares course = input<Course | null>(); without it, read inject(ActivatedRoute).data. The same inputs mechanism from the previous lesson applies.

Resolvers have trade-offs you should know:

  • The navigation waits. Until every resolver completes, the URL doesn't change and the old page stays visible. A slow API makes the app feel frozen unless you show progress (see the events below).
  • An error cancels the navigation with a NavigationError. Catch errors in the resolver and return a fallback, or redirect, as appropriate.
  • Resolvers suit data the page cannot work without (the course the page is about). For data that can arrive later, load it inside the component with a resource and show a skeleton instead.

Router events

The Router exposes events, an observable of everything that happens during navigation. The most useful events are:

  • NavigationStart: a navigation has been triggered.
  • GuardsCheckEnd and ResolveEnd: guards and resolvers finished.
  • NavigationEnd: success, the URL has been updated.
  • NavigationCancel: a guard blocked or redirected it.
  • NavigationError: something threw, for example a resolver.
  • NavigationSkipped: the user asked for the URL they are already on.

A classic use is a global progress bar:

TypeScript
import { Component, inject } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { NavigationCancel, NavigationEnd, NavigationError, NavigationStart, Router } from '@angular/router';
import { filter, map } from 'rxjs';

@Component({
  selector: 'app-progress',
  template: `@if (loading()) { <div class="bar" role="progressbar" aria-label="Loading page"></div> }`,
})
export class ProgressComponent {
  readonly loading = toSignal(
    inject(Router).events.pipe(
      filter((e) => e instanceof NavigationStart || e instanceof NavigationEnd
        || e instanceof NavigationCancel || e instanceof NavigationError),
      map((e) => e instanceof NavigationStart),
    ),
    { initialValue: false },
  );
}

The start event turns the flag on, and any of the three finishing events turn it off. Remember that all three outcomes need handling, or the bar would stay on after a blocked navigation.

A runnable resolver and event log

This stand-in router checks a canDeactivate function, runs async resolvers, and emits events. A listener turns them into a spinner flag exactly like the component above.

TypeScript Stand-in: resolvers, events and a loading flag

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Every navigation ends with exactly one of NavigationEnd, NavigationCancel or NavigationError, which is why the spinner is guaranteed to switch off. In the failing case the user simply stays on the previous URL, which is what the real router does as well.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What should a canActivate guard return to send an unauthenticated user to the login page?

    Returning a UrlTree cancels the current navigation and starts a new one to that URL. Strings are not valid guard results.
  2. 2. Which guard decides whether a lazy route is even matched, without downloading its chunk?

    canMatch runs during route matching. If it returns false the route is skipped, so the lazy code is never fetched. It supersedes canLoad.
  3. 3. A teammate says "we hide the admin routes with a guard, so the admin API doesn't need permission checks." What is wrong with that?

    Everything in an Angular app runs in the user's browser and can be altered. Guards improve the experience; the server remains responsible for security.
  4. 4. What happens to a navigation while its resolver is still running?

    The router activates the route only after resolvers complete. That is why slow resolvers need a progress indicator based on router events.
  5. 5. Which events mean a navigation finished without succeeding?

    Cancel (for example a guard returned false) and Error (for example a resolver threw) are the unsuccessful endings. NavigationEnd is the success event.

Summary

  • Functional guards (CanActivateFn, CanMatchFn, CanActivateChildFn, CanDeactivateFn) use inject() and return true, false, a UrlTree, or an async version of those.
  • Redirect by returning a UrlTree; include a returnUrl if the user should come back after logging in.
  • Use canMatch to keep lazy routes unavailable, canActivate for access control and canDeactivate for unsaved changes. Guards are UX, not security.
  • Resolvers (resolve: { key: resolverFn }) load data before activation; the navigation waits and an error cancels it, so handle failures in the resolver.
  • Router.events reports every stage; each navigation ends with NavigationEnd, NavigationCancel or NavigationError, which is what a loading indicator should key on.
  • The Angular code here is read-only; the guard pipeline and mini router are stand-ins.

Next: Template-Driven Forms