Sub topic 11
Loading data before activation with ResolveFn
This chapter assumes you can write a Routes array, read route parameters, build an Angular service that returns Observables, and use inject() inside a function. Guards decide whether a navigation may proceed. A resolver answers a different question: what data must exist before the route's component appears?
What a resolver does
A resolver is a function that the router runs while a navigation is in progress. The router waits for its result, stores it on the route, and only then activates the component. The component can assume its data is already there.
The alternative is to fetch inside the component. In that case the component renders first, and your template must handle an empty state until the request finishes. Both approaches are valid. A resolver trades a blank wait on the previous page for a component that never renders half-empty.
The type for a functional resolver is ResolveFn<T>. It receives two arguments:
route: anActivatedRouteSnapshotwith the parameters, query parameters, and static data of the route being activated.state: aRouterStateSnapshotwith the full target URL instate.url.
It may return T, a Promise<T>, or an Observable<T>.
Writing a resolver
This resolver reads the id parameter and returns an Observable of the product.
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);
};inject() works here because the router calls the resolver inside an injection context. Call inject() synchronously at the top of the function, before any await or callback. Calls made later in an async function or inside .pipe() operators fail with a missing injection context error.
The ! after get('id') tells TypeScript the parameter exists. That is safe only when the route path contains :id. If you reuse the resolver on a route without that parameter, id will be null at runtime.
Attaching it to a route
Resolvers are registered in the resolve property of a route. It is a map from a key to a resolver function.
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),
},
];The key product becomes the name under which the resolved value is stored. You can list several resolvers in one resolve map. The router runs them in parallel, so independent requests do not wait for each other.
How the router waits for an Observable
The router does not treat every Observable the same way. It uses the first emitted value and then stops waiting. That has two consequences:
- A long-lived Observable, such as a stream from a WebSocket or a
BehaviorSubject, will not keep updating the resolved data. The router takes the first value and moves on. - An Observable that completes without emitting any value cancels the navigation. The router sees "no value" and the user stays on the current page, with no error shown.
The second case is easy to hit with operators such as EMPTY, filter, or first() on an empty stream. If your resolver can legitimately find nothing, return a value that represents it, such as null, instead of completing silently.
import { Observable, of } from 'rxjs';
import { delay } from 'rxjs/operators';
// Emits one value after 500 ms, then completes. The router proceeds.
const works$: Observable<string> = of('data').pipe(delay(500));
// Completes without a value. The navigation is cancelled.
// const stuck$ = EMPTY;Where resolvers sit in the navigation
Resolvers run only after the guards on the route allow the navigation. This is useful: an anonymous user who is redirected to the login page never triggers the product request. The next chapters cover reading the data and the error cases. The full order is covered in its own chapter, so here the point is simply that resolvers come after guards.
Resolvers and route reuse
By default, the router reuses a component instance when only the parameters change, for example when moving from /products/1 to /products/2. It still runs the resolver again in that case, but only under the right conditions. The setting that controls this is runGuardsAndResolvers on the route. Its values are:
| Value | Resolvers re-run when |
|---|---|
| `paramsChange` (default) | Path or matrix parameters change |
| `paramsOrQueryParamsChange` | Path, matrix, or query parameters change |
| `pathParamsChange` | Only path parameters change |
| `always` | Every navigation to the route, even to the same URL |
| a function | The function returns `true` |
If your resolver depends on a query parameter, such as a search term or page number, the default setting will not refresh the data when only that query parameter changes. Set runGuardsAndResolvers: 'paramsOrQueryParamsChange' on that route.
{
path: 'products',
runGuardsAndResolvers: 'paramsOrQueryParamsChange',
resolve: { page: productPageResolver },
loadComponent: () => import('./product-list.component').then(m => m.ProductListComponent),
}Inheritance and static data
Resolved data is also visible to child routes, but only when the parent has a component or is a componentless route that passes data through. With the default paramsInheritanceStrategy: 'emptyOnly', a child inherits the parent's resolved data only when the parent has an empty path or no component. Otherwise, the child must read the parent's data through route.parent. If a child cannot find data you resolved on its parent, check this setting before changing the resolver.
Resolved data is merged with the static data property of the route. If a key appears in both, the resolved value wins. Avoid using the same key in both places.
Common mistakes
- Fetching in the resolver and again in the component. If the resolver already loaded the product, read it from the route. A second request wastes bandwidth and can produce a value that differs from the first.
- Resolving slow, optional data. The user waits on the previous page for every resolver. Resolve only what the page cannot meaningfully render without, and load secondary data in the component.
- Calling
inject()after anawait. The injection context is gone. Inject services at the top. - Expecting live updates. The router takes one value. Subscribe in the component for streams.
- Silent cancellation. A resolver that completes empty leaves the user stuck on the old page. Return
nullor a fallback value.
When to use a resolver and when not to
Use a resolver when:
- the component cannot show a useful page without the data,
- a failure should prevent navigation or redirect elsewhere, and
- you want the data request to start only after guards have passed.
Prefer fetching in the component when:
- the page has a sensible loading state and partial content to show,
- the data is large or slow, and the user benefits from seeing the layout right away, or
- the data depends on user interaction after the page loads.
Exercises
Exercise
A route products/:id has a resolver that returns inject(ProductService).getById(id).pipe(filter(p => p.isPublished)). When the product is not published, the user clicks a link and nothing happens, and no error appears. Why, and how would you fix it?
Show answer
The filter removes the only emitted value, so the Observable completes without emitting. The router treats a resolver that completes without a value as a cancelled navigation, so the user stays on the previous page. Remove the filter and return the product (or null) so the component or a redirect can handle the unpublished case, or use catchError and return a RedirectCommand to a not-found page.
Exercise
Your product list route resolves a page of results using the page query parameter. Moving from /products?page=1 to /products?page=2 shows the old results. What route property do you change, and to what?
Show answer
Set runGuardsAndResolvers: 'paramsOrQueryParamsChange' on the route. The default, paramsChange, re-runs resolvers only when path or matrix parameters change, so a query parameter change does not trigger the resolver again.