Sub topic 11
Loading data before activation with ResolveFn
This chapter assumes you know Angular routing basics, RxJS Observables, and inject(). It covers how to write a resolver and attach it to a route. Reading the data in a component and handling failures are covered in later chapters.
What a resolver does
A resolver is a function that the router runs before it activates a route. The router waits for it to finish. Only then does it create the component. The component starts with its data already loaded, so it never shows an empty state while a request is in flight.
A resolver is typed as ResolveFn<T>, where T is the type of the data it produces. It receives the same ActivatedRouteSnapshot and RouterStateSnapshot that guards receive. It may return a plain value, a Promise<T>, or an Observable<T>.
Writing a resolver
A resolver is a plain function. Because the router calls it inside an injection context, you can call inject() to get services.
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 route snapshot holds the route parameters. Here paramMap.get('id') reads the :id segment of the URL. The non-null assertion (!) is safe only because the route path declares :id.
Attaching it to a route
You attach resolvers with the resolve property. It is an object, and 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),
},
];The key product is the name you will use to read the data later. You can list several resolvers in the same object, and the router runs them in parallel.
How the router waits
The router subscribes to the Observable and uses the first value it emits. The Observable must complete, or emit at least once, or the navigation never finishes. An HttpClient call completes after one response, so it works as is. A long-lived stream such as a store selector does not complete. Add take(1) or first() to it.
Resolvers run only after the guards pass. A user who fails canActivate never triggers the resolver's request.
Common mistakes
- Never-completing streams. The navigation hangs with no error. Apply
take(1)orfirst(). - Slow resolvers. The old page stays on screen until the data arrives. Keep resolvers for data the page cannot sensibly render without.
- Reading the wrong snapshot. Use the
routeargument for parameters of the route being resolved, notActivatedRouteinjected from elsewhere.
Exercise
A resolver returns inject(Store).select(selectProduct), an Observable that emits the current product and then keeps emitting on every change. Navigation to the route never completes. Why, and how do you fix it?
Show answer
The router needs the resolver's Observable to emit a value and complete, or at least to have a first value it can take. This stream stays open, so the router keeps waiting. Pipe it through take(1) or first() so the Observable completes after the first emission.