Sub topic 10
The order in which guards and resolvers run
This chapter assumes you can write a Routes array, have used canActivate and ResolveFn at a basic level, and know that guards can return a boolean, a UrlTree, an Observable, or a Promise. Here you learn the exact sequence the router follows, so you can predict which guard runs first, when a resolver fires, and what happens when one step fails.
Why order matters
Guards and resolvers are separate mechanisms, but they run in one pipeline. Order decides several practical things:
- Whether a resolver makes an HTTP call for a user who was never allowed to see the page.
- Whether a lazy-loaded bundle is downloaded before a permission check.
- Whether the "unsaved changes" prompt appears before or after a login redirect.
If you guess the order wrong, you end up with wasted requests, flashes of the wrong page, or checks that run too late to help.
The navigation pipeline
When a navigation starts, the router first matches the URL against your route configuration and builds the new router state. It then runs checks in a fixed sequence. The simplified version is:
canMatchruns during matching, while the router decides which route configuration applies.canDeactivateruns on the components being left.canActivateChildruns on parent routes, for the children being entered.canActivateruns on the routes being entered.resolveruns for the routes being entered, after every guard has passed.- The router activates the new components and updates the URL.
The key rule: all guards finish before any resolver starts. A resolver never runs for a navigation that a guard has rejected.
canMatch runs first, and affects lazy loading
canMatch participates in route matching itself. If it returns false, the router treats that route as if it did not exist and tries the next candidate in the array. This is why it is the right place to gate lazy-loaded routes: the route's loadChildren or loadComponent is not triggered when matching is skipped.
import { inject } from '@angular/core';
import { CanMatchFn, Routes } from '@angular/router';
import { AuthService } from './auth.service';
export const adminMatchGuard: CanMatchFn = () => inject(AuthService).isAdmin();
export const routes: Routes = [
{
path: 'dashboard',
canMatch: [adminMatchGuard],
loadComponent: () =>
import('./admin-dashboard.component').then(m => m.AdminDashboardComponent),
},
{
path: 'dashboard',
loadComponent: () =>
import('./user-dashboard.component').then(m => m.UserDashboardComponent),
},
];Two routes share the path dashboard. For an admin, the first matches. For everyone else, canMatch returns false, the router moves on, and the second route matches. The admin bundle is never downloaded for non-admins.
Compare this with canActivate, which runs after the route has already matched. For a lazy route, canActivate can still run before the component code loads in some configurations, but only canMatch guarantees that a failed check skips the route entirely and lets another route take over.
Deactivation before activation
canDeactivate is checked on the components you are leaving, and it runs before the guards for the destination. That ordering is deliberate. If the user has unsaved changes, they are asked first. Only after they agree does the router check whether the destination is allowed.
This has a side effect worth knowing. A user can confirm "Leave this page?" and then be redirected to /login by a canActivate guard on the destination. The confirmation was shown even though the navigation then failed. If that is a problem, you cannot reorder the guards. You can make the destination check cheaper to predict, for example by hiding links the user cannot follow.
Parent before child, and the canActivateChild step
Within each kind of guard, the router runs checks from the top of the route tree downward. For a URL like /shop/products/42, the parent shop route is checked before the child products/:id route.
canActivateChild is defined on the parent but runs for each child being entered. A parent canActivate runs once when the parent is entered. A parent canActivateChild runs again when the user moves between its children.
import { Routes } from '@angular/router';
import { authGuard } from './auth.guard';
import { auditGuard } from './audit.guard';
import { productResolver } from './product.resolver';
export const routes: Routes = [
{
path: 'shop',
canActivate: [authGuard],
canActivateChild: [auditGuard],
children: [
{
path: 'products/:id',
resolve: { product: productResolver },
loadComponent: () =>
import('./product-detail.component').then(m => m.ProductDetailComponent),
},
],
},
];Navigating to /shop/products/42 for the first time runs, in this order:
authGuard(canActivate onshop).auditGuard(canActivateChild, for the childproducts/:id).productResolver.
Moving from /shop/products/42 to /shop/products/43 does not re-enter shop, so authGuard does not run again. auditGuard does run, because a child is being entered.
Multiple guards on one route
Guards in an array run in the order you list them. Since Angular 7.1, a failure result stops the rest of the array from being consulted for that guard type. The router waits for each guard to finish, in sequence, and uses the first result that is not true.
{
path: 'billing',
canActivate: [authGuard, subscriptionGuard],
loadComponent: () =>
import('./billing.component').then(m => m.BillingComponent),
}Put the cheapest and most general check first. Here authGuard runs before subscriptionGuard, so an anonymous user is redirected to login without a subscription lookup.
When several guards return different UrlTree results, the first non-true result wins. Do not rely on all guards running to completion.
Resolver ordering
Resolvers run after all guards pass. A few details matter:
- Resolvers for the same route run in parallel. Each key in the
resolvemap starts independently. - The router waits for every resolver to emit before it activates. If one resolver is slow, the whole navigation is slow.
- A resolver is considered finished when its
Observableemits its first value and completes, or, in current Angular versions, when it emits at least once. An observable that completes without emitting cancels the navigation. - Parent resolvers are run alongside child resolvers in the same stage. A child resolver can read the parent's resolved data only through
route.parentorinheritedDataand should not assume parent data is complete when the child resolver starts.
The practical consequence: keep resolvers independent. If one resolver needs the result of another, combine them into one resolver or move the dependent call into the component.
Resolver run frequency
By default a resolver runs only when the route's parameters change. Navigating between two query-string values on the same route does not re-run it. The runGuardsAndResolvers option on the route changes this:
| Value | When guards and resolvers re-run |
|---|---|
| `'paramsChange'` (default) | Path or matrix parameters change |
| `'paramsOrQueryParamsChange'` | Path, matrix, or query parameters change |
| `'pathParamsChange'` | Only path parameters change |
| `'always'` | Every navigation to this route, including to the same URL |
| A function | Your own comparison of the previous and next route |
{
path: 'search',
runGuardsAndResolvers: 'paramsOrQueryParamsChange',
resolve: { results: searchResolver },
loadComponent: () =>
import('./search.component').then(m => m.SearchComponent),
}This option applies to guards and resolvers together. You cannot ask for guards to re-run while leaving resolvers alone.
Failure and cancellation
What a failing step does depends on its type.
| Step result | Effect on the navigation |
|---|---|
| Guard returns `false` | Navigation is cancelled and the current URL stays |
| Guard returns a `UrlTree` | Current navigation is cancelled and a new one starts to that URL |
| Guard or resolver throws or errors | Navigation fails with an error, handled by the router's error handling |
| Resolver completes without a value | Navigation is cancelled |
| Resolver returns a `RedirectCommand` | Navigation redirects to the given URL (Angular 18 and later) |
| A newer navigation starts | The in-flight navigation is cancelled |
The last row matters for slow async guards. If a user clicks a second link while a guard is still waiting on a server, the router drops the first navigation. A guard that performs side effects, such as logging or analytics, may begin work for a navigation that is later abandoned. Keep guards free of side effects that cannot be safely abandoned.
Observing the order yourself
The most reliable way to confirm the order is to log it. This example uses three guards and one resolver that print a label when they run.
import { CanActivateChildFn, CanActivateFn, CanDeactivateFn, ResolveFn } from '@angular/router';
export const logDeactivate: CanDeactivateFn<unknown> = () => {
console.log('1 canDeactivate');
return true;
};
export const logChild: CanActivateChildFn = () => {
console.log('2 canActivateChild');
return true;
};
export const logActivate: CanActivateFn = () => {
console.log('3 canActivate');
return true;
};
export const logResolve: ResolveFn<string> = () => {
console.log('4 resolve');
return 'done';
};Attach them to a parent route with a child route, navigate between two pages, and read the console. You will see the numbers appear in ascending order. Add a guard that returns false and notice that 4 resolve never prints.
Summary of rules
canMatchruns during matching and can make the router skip a route and avoid a lazy download.canDeactivateruns before any destination guard.canActivateChildandcanActivaterun from parent to child.- Every guard must pass before any resolver starts.
- Resolvers on a route run in parallel and the navigation waits for the slowest.
runGuardsAndResolverscontrols re-runs for both guards and resolvers.
Exercise
A route /reports/:id has canActivate: [authGuard] and resolve: { report: reportResolver }. An anonymous user opens a link to /reports/7. Does reportResolver make its HTTP request? Then name the option that would make the resolver run again when only the query string changes from ?page=1 to ?page=2.
Show answer
No. All guards run before any resolver, and authGuard rejects the anonymous user (returning false or a UrlTree), so the navigation ends before the resolver starts and no request is made. To re-run the resolver on query string changes, set runGuardsAndResolvers: 'paramsOrQueryParamsChange' on the route. This also re-runs the guards on that route.
Exercise
You have two routes with the same path account. The first has canMatch: [premiumGuard] and loads a large premium bundle. The second loads a basic bundle. A free user visits /account. Which bundle is downloaded, and why is canActivate a poor substitute here?
Show answer
Only the basic bundle. premiumGuard returns false, so the router treats the first route as not matching and moves to the second. The premium bundle is never requested. With canActivate the route would already have matched, so a failure would cancel or redirect the navigation instead of falling through to the second route, and the router would not choose the basic route automatically.