Sub topic 2
What guards and resolvers are for
This chapter explains the two jobs that sit between "the user asked for a URL" and "the component appears." It assumes you know basic TypeScript, Angular components and services, the Routes array, router-outlet, routerLink, route parameters, and the basics of dependency injection and RxJS. Later chapters cover each guard type in detail. Here you learn what problem each tool solves and how to choose between them.
The problem: the router activates by default
By default, the Angular router does exactly what the URL says. If the URL matches a route, the router creates the component and shows it. That is fine for public pages. It causes trouble in three common cases:
- The user is not allowed to see the page, for example because they are not logged in.
- The user is leaving a page that holds work they have not saved.
- The component needs data from a server, and the page looks broken or empty until that data arrives.
Angular gives you two features for these cases. Guards decide whether a navigation may proceed. Resolvers load data before the route activates.
Where guards and resolvers sit in a navigation
A navigation is not a single step. The router matches the URL against your route configuration, runs checks, and only then updates the view. The diagram shows the main stages that matter for this chapter.
The key idea is that all of this happens before the new component is created. If a guard says no, the user stays where they were, or the router sends them somewhere else. If a resolver is slow, the old page stays visible until it finishes. The exact order of each check is covered in a later chapter.
What a guard is
A guard is a function that the router calls during navigation. It answers one question: may this navigation continue? In modern Angular, a guard is a plain function that can call inject() to reach services. It can return:
trueto allow the navigation.falseto cancel it.- A
UrlTreeto cancel it and redirect to another URL.
It can also return a Promise or an Observable of those values, so it can wait for a server answer.
There are four guard types, each tied to a different moment:
| Guard | Question it answers | Typical use |
|---|---|---|
| `canActivate` | May the user enter this route? | Require login |
| `canActivateChild` | May the user enter any child of this route? | Protect a whole section |
| `canDeactivate` | May the user leave this route? | Warn about unsaved changes |
| `canMatch` | Should this route configuration be considered at all? | Hide routes by role, skip lazy loading |
Here is a complete guard for the most common case.
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 asks AuthService whether the user is logged in. If so, navigation proceeds. If not, it returns a UrlTree pointing at /login, and it stores the requested URL in a returnUrl query parameter so the login page can send the user back afterward.
Returning a UrlTree is usually better than calling router.navigate() inside the guard and returning false. With a UrlTree, the router handles the redirect as part of the same navigation, so the browser history and any pending navigation state stay consistent.
What a resolver is
A resolver is also a function the router calls during navigation. Instead of answering yes or no, it produces data. The router waits for it, stores the result on the route, and only then activates the component.
import { inject } from '@angular/core';
import { ResolveFn } from '@angular/router';
import { Product, ProductService } from './product.service';
export const productResolver: ResolveFn<Product> = (route) => {
const id = route.paramMap.get('id')!;
return inject(ProductService).getById(id);
};The resolver reads the id route parameter and returns an Observable<Product> from a service. The router subscribes, waits for the value, and passes it along. A resolver can return a plain value, a Promise, or an Observable.
Attaching both to a route
You attach guards and resolvers in the route configuration. Guards go in arrays under their guard names. Resolvers go in a resolve map, where each key becomes the name of the resolved data.
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),
},
];When the user navigates to /products/42, the router first runs authGuard. If that passes, it runs productResolver. Only after both succeed does ProductDetailComponent appear, with the data available under the name product.
Choosing between a guard and a resolver
The two tools are easy to confuse because both delay navigation. Use this rule: if the question is "should this happen?", use a guard. If the question is "what does this page need?", use a resolver.
Some practical points help with the decision:
- A guard's output is a decision. A resolver's output is data the component reads.
- If the only reason for the delay is that the component needs data, a resolver is a good fit. The component can assume the data exists.
- If you could also fetch the data inside the component and show a spinner, consider that option. Resolvers hold the user on the previous page, which can feel slow if the request takes a while.
- Never put access decisions in a resolver. A resolver that fails is an error case, not a policy check.
Common mistakes
- Treating guards as security. A guard runs in the user's browser, so a determined user can bypass it. It improves the experience by hiding pages that would not work for them. Your server must still check permissions on every request. A later chapter covers this in depth.
- Doing slow work in guards without thinking about the delay. Every awaited call in a guard or resolver keeps the user waiting on the old page. Keep these functions fast, and give feedback during slow navigations.
- Calling
inject()outside the guard's synchronous start.inject()works only in an injection context. Call it at the top of the function, before anyawaitor asynchronous callback. - Navigating manually and returning
false. Return aUrlTreeinstead, so the redirect is part of the same navigation.
Summary of the mental model
- Guards decide whether a navigation continues, is cancelled, or is redirected.
- Resolvers fetch data so the component has it on arrival.
- Both run before the new component is created, and both can delay the navigation.
- Both are configured on the route, and both use
inject()to reach services.
Exercise
A product detail page needs the product record from the server, and only logged-in users may see it. Which feature handles each requirement, and what should the guard return for an anonymous user so the user ends up on the login page?
Show answer
A guard (canActivate) handles the login requirement, and a resolver handles loading the product. For an anonymous user, the guard should return a UrlTree for /login, created with router.createUrlTree(['/login']), rather than calling navigate() and returning false. Returning UrlTree makes the redirect part of the same navigation.
Exercise
Why is it a mistake to rely on an authGuard alone to protect sensitive data?
Show answer
Guards run in the browser, so a user can modify or bypass client code, or call your API directly. The server must check authorization on each request. The guard only improves the user experience by keeping users away from pages they cannot use.