Sub topic 12
Loading Data Before Navigation with Resolvers
This chapter assumes you already know how to define routes, read route parameters, and write functional guards (all covered in earlier chapters). You should also know basic RxJS operators such as map and catchError, and how Angular services use HttpClient.
Why Resolvers Exist
A routed component usually needs data before it can show anything useful. A product detail page needs the product, and a profile page needs the user. One option is to activate the component right away and fetch the data in its constructor or ngOnInit. The component then has to handle a "loading" state and a "not found" state on its own.
A resolver is a function the router calls during navigation, before it activates the target component. The router waits for the resolver's result and stores it in the route's data. The component appears only after the data is ready. If the data can't be loaded, the resolver can cancel the navigation or redirect, and the broken page never renders.
| Approach | When the component renders | Who handles missing data | User sees |
|---|---|---|---|
| Fetch in component | Immediately | The component | Old page replaced by a spinner or skeleton |
| Resolver | After data arrives | The resolver, before activation | Old page stays until the new one is complete |
Neither approach wins every time. Resolvers keep components simple and stop half-rendered pages from appearing. They also delay the visible navigation by however long the request takes.
Where Resolvers Run in a Navigation
The router processes a navigation in phases. It matches the URL against the route config, runs guards, and then runs resolvers. It activates components only after all of those finish. Because resolvers run after guards, a resolver never fetches data for a user who isn't allowed on the route.
Writing a Resolver
A resolver has the type ResolveFn<T>. It receives the ActivatedRouteSnapshot of the route being activated and the RouterStateSnapshot. It can return a plain value, a Promise, or an Observable. Like functional guards, it runs in an injection context, so inject() works inside it.
Start with a small service:
// product.service.ts
import { Injectable, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
export interface Product {
id: string;
name: string;
price: number;
}
@Injectable({ providedIn: 'root' })
export class ProductService {
private http = inject(HttpClient);
getProduct(id: string): Observable<Product> {
return this.http.get<Product>(`/api/products/${id}`);
}
}The simplest resolver reads the id parameter and returns the service call:
// product.resolver.ts
import { inject } from '@angular/core';
import { ResolveFn } from '@angular/router';
import { Observable } from 'rxjs';
import { Product, ProductService } from './product.service';
export const productResolver: ResolveFn<Product> = (route): Observable<Product> => {
const id = route.paramMap.get('id')!;
return inject(ProductService).getProduct(id);
};Register it under a key in the route's resolve object. The key becomes the property name in the route's data:
// app.routes.ts
import { Routes } from '@angular/router';
import { ProductDetailComponent } from './product-detail.component';
import { productResolver } from './product.resolver';
export const routes: Routes = [
{
path: 'products/:id',
component: ProductDetailComponent,
resolve: { product: productResolver }
}
];Reading Resolved Data in the Component
You can read resolved data in two ways.
With withComponentInputBinding() enabled in provideRouter, the router binds each resolve key to a component input of the same name. It binds route parameters and query parameters the same way:
// product-detail.component.ts
import { Component, Input } from '@angular/core';
import { CurrencyPipe } from '@angular/common';
import { Product } from './product.service';
@Component({
selector: 'app-product-detail',
standalone: true,
imports: [CurrencyPipe],
template: `
<h2>{{ product.name }}</h2>
<p>{{ product.price | currency }}</p>
`
})
export class ProductDetailComponent {
@Input() product!: Product;
}Without input binding, inject ActivatedRoute and read its data Observable. Use the Observable instead of snapshot.data. The router reuses the component when only the parameter changes, for example from /products/1 to /products/2. When that happens, data emits the new product, but the snapshot you read in the constructor still holds the old one.
import { Component, inject } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { AsyncPipe, CurrencyPipe } from '@angular/common';
import { map } from 'rxjs';
import { Product } from './product.service';
@Component({
selector: 'app-product-detail',
standalone: true,
imports: [AsyncPipe, CurrencyPipe],
template: `
@if (product$ | async; as product) {
<h2>{{ product.name }}</h2>
<p>{{ product.price | currency }}</p>
}
`
})
export class ProductDetailComponent {
private route = inject(ActivatedRoute);
product$ = this.route.data.pipe(map(data => data['product'] as Product));
}Handling Errors and Missing Data
When a resolver's Observable errors, the router cancels the navigation and emits a NavigationError event. The user stays on the previous page with no explanation, and the error may surface as an unhandled rejection. Handle failures inside the resolver.
In Angular 18 and later, a resolver can return a RedirectCommand to send the user somewhere else:
// product.resolver.ts
import { inject } from '@angular/core';
import { RedirectCommand, ResolveFn, Router } from '@angular/router';
import { catchError, of } from 'rxjs';
import { Product, ProductService } from './product.service';
export const productResolver: ResolveFn<Product> = (route) => {
const router = inject(Router);
const id = route.paramMap.get('id')!;
return inject(ProductService).getProduct(id).pipe(
catchError(() =>
of(new RedirectCommand(router.parseUrl('/not-found'), { skipLocationChange: true }))
)
);
};skipLocationChange: true keeps the original URL in the address bar while the not-found page renders. The user can still see which URL failed and reload it.
You can respond to a failed load in other ways:
- Return
EMPTYto cancel the navigation and keep the user on the current page. Pair this with a toast or other message, or the click looks like it did nothing. - Return a fallback value such as
null, and type the resolver asResolveFn<Product | null>. The component then handles the missing case, which removes part of the reason for using a resolver. - Use
withNavigationErrorHandler()inprovideRouterto handle uncaught navigation errors in one place across the whole app.
When Resolvers Re-run
By default, the router re-runs guards and resolvers when the route's path or matrix parameters change. A change to only the query parameters or the fragment does not re-run them. Control this with runGuardsAndResolvers on the route:
| Value | Re-runs when |
|---|---|
| `'paramsChange'` (default) | Path or matrix params change |
| `'pathParamsChange'` | Path params change, ignoring matrix params |
| `'paramsOrQueryParamsChange'` | Path, matrix, or query params change |
| `'always'` | Every navigation to the route |
| function `(from, to) => boolean` | Your function returns `true` |
A product list that reads ?page=2 through a resolver needs 'paramsOrQueryParamsChange'. Without it, paging updates the URL but the list keeps showing page 1.
Resolvers on Parent and Child Routes
Resolvers on a parent route finish before the child's resolvers start. The resolvers on a single route run in parallel. A child resolver can read parent data from route.parent?.data. Child components see a parent's resolved data on their own ActivatedRoute only when the parent is componentless (a pure grouping route), or when you set paramsInheritanceStrategy: 'always' through withRouterConfig. Put shared data, such as a current account, on the parent so it loads once for the whole section.
Common Mistakes
- Slow resolvers with no feedback. The old page stays visible while the request runs, so the click seems ignored. Show a progress bar driven by router events (covered in the next chapter).
- Expensive work in resolvers. Every navigation waits for every resolver. Resolve only what the page can't render without, and load secondary data inside the component.
- Reading
snapshot.datain a reused component. The page shows stale data after a parameter change. Use input binding orroute.data. - Unhandled errors. Without
catchError, a 404 turns into a silent cancelled navigation. - Using resolvers for access control. Guards already ran before resolvers. Keep authorization in guards and data loading in resolvers.
Exercise
A route orders uses ordersResolver, which reads route.queryParamMap.get('status'). Clicking a link from /orders?status=open to /orders?status=closed changes the URL, but the list still shows open orders. Why, and what is the fix?
Show answer
By default, runGuardsAndResolvers is 'paramsChange', which ignores query parameter changes. The router reuses the component and does not call the resolver again. Set runGuardsAndResolvers: 'paramsOrQueryParamsChange' on the orders route. Also make sure the component reads the data through input binding or route.data, not snapshot.data.
Exercise
A resolver returns this.store.select(selectCurrentUser), where the store starts with null and fills in the user after an HTTP call. The component always receives null. Explain the cause and write a corrected return statement.
Show answer
The router takes the first value an Observable emits. The store emits its initial null right away, so that is the value that gets resolved. Filter it out and take one value: return inject(Store).select(selectCurrentUser).pipe(filter((u): u is User => u !== null), take(1));
Exercise
Your product resolver lets HTTP errors propagate. A user clicks a link to a deleted product. What happens, and name two ways to give a better result?
Show answer
The Observable errors, the router cancels the navigation and emits NavigationError, and the user stays on the current page with no feedback. Better options: catch the error in the resolver and return a RedirectCommand to a not-found page (optionally with skipLocationChange: true), or catch it, show a message, and return EMPTY to cancel on purpose. You can also add withNavigationErrorHandler() as an app-wide fallback.