Sub topic 12
Reading resolved data in a component
This chapter assumes you can write a ResolveFn and attach it to a route with the resolve map. It also assumes you know basic RxJS and Angular signals. Here you will learn how the data a resolver returns reaches your component, and which mistakes cause it to arrive missing or stale.
Where resolved data lives
When all resolvers for a route finish, the router stores each result under the key you used in the resolve map. The key product in resolve: { product: productResolver } becomes the name of the data. The router places that data in two places:
ActivatedRoute.data, an Observable that emits an object such as{ product: ... }.ActivatedRoute.snapshot.data, a plain object holding the values at the moment of activation.
Resolvers run before the component is created. By the time your constructor runs, the data already exists, so the component needs no loading state of its own for this data.
Approach 1: ActivatedRoute.data
The most explicit approach injects ActivatedRoute and reads data. Convert the Observable to a signal so the template can read it directly.
import { Component, inject } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { toSignal } from '@angular/core/rxjs-interop';
import { map } from 'rxjs';
import { Product } from './product.service';
@Component({
selector: 'app-product-detail',
standalone: true,
template: `<h1>{{ product().name }}</h1>`,
})
export class ProductDetailComponent {
private route = inject(ActivatedRoute);
product = toSignal(
this.route.data.pipe(map((data) => data['product'] as Product)),
{ requireSync: true },
);
}requireSync: true is valid because ActivatedRoute.data emits its current value as soon as you subscribe. It removes undefined from the signal's type. Without it, product() would be typed Product | undefined.
The data object is indexed by string, so TypeScript cannot check the key or the type. The as Product cast is your promise to the compiler. If the key is misspelled, you get undefined at runtime.
Approach 2: component input binding
If you enable withComponentInputBinding(), the router sets component inputs for you. This is the example from the chapter's code samples:
import { Component, input } from '@angular/core';
import { Product } from './product.service';
@Component({
selector: 'app-product-detail',
standalone: true,
template: `<h1>{{ product().name }}</h1>`,
})
export class ProductDetailComponent {
product = input.required<Product>();
}
// In app config: provideRouter(routes, withComponentInputBinding())The input name must equal the resolve key. The component no longer imports ActivatedRoute, which makes it easier to test: you set the input and nothing else. The component can also be reused outside the router.
The same feature binds path parameters and query parameters to inputs with matching names. When names collide, route data takes priority over path parameters, and path parameters take priority over query parameters. A resolve key named id would therefore hide a path parameter named id. Choose distinct names.
Comparing the two approaches
| Concern | `ActivatedRoute.data` | Input binding |
|---|---|---|
| Setup | None | `withComponentInputBinding()` in `provideRouter` |
| Typing | Cast from `any` | Declared on the input |
| Testing | Needs a fake `ActivatedRoute` | Set the input directly |
| Coupling to the router | Direct | Indirect |
| Also binds params and query params | No | Yes |
Reading the snapshot, and why it goes stale
You can read this.route.snapshot.data['product'] once. That is fine if the component is always destroyed and recreated between navigations.
The router often does not do that. When you navigate from /products/1 to /products/2, the route configuration is the same, so the router reuses the existing component instance. The resolver runs again and route.data emits the new product, but a value copied from the snapshot in the constructor still shows product 1.
import { Component, inject } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-stale-example',
standalone: true,
template: `<h1>{{ product.name }}</h1>`,
})
export class StaleExampleComponent {
// Bug: read once. It will not update when only :id changes.
product = inject(ActivatedRoute).snapshot.data['product'];
}Both the Observable approach and the input approach avoid this problem, because each updates when the router reuses the component. Use the snapshot only when you are sure the component is never reused for sibling URLs.
When the resolver runs again
A resolver does not run on every navigation. By default the router re-runs guards and resolvers for a route only when its path or matrix parameters change (runGuardsAndResolvers: 'paramsChange'). Query parameter changes do not trigger it. If your resolver depends on a query parameter such as ?sort=price, the data stays stale unless you opt in:
import { Routes } from '@angular/router';
import { productListResolver } from './product-list.resolver';
export const routes: Routes = [
{
path: 'products',
runGuardsAndResolvers: 'paramsOrQueryParamsChange',
resolve: { products: productListResolver },
loadComponent: () =>
import('./product-list.component').then((m) => m.ProductListComponent),
},
];The other values are 'pathParamsChange', 'pathParamsOrQueryParamsChange', and 'always'. Use 'always' sparingly, because it re-runs the resolver on every navigation to that route.
Data from parent routes
A child route can read data resolved on a parent route. Since Angular 16 the router inherits parent data by default through the paramsInheritanceStrategy option of withRouterConfig. The default is 'emptyOnly', which inherits only when the parent has an empty path or is componentless. With 'always', every child inherits all parent params, data, and resolved values:
import { ApplicationConfig } from '@angular/core';
import { provideRouter, withComponentInputBinding, withRouterConfig } from '@angular/router';
import { routes } from './app.routes';
export const appConfig: ApplicationConfig = {
providers: [
provideRouter(
routes,
withComponentInputBinding(),
withRouterConfig({ paramsInheritanceStrategy: 'always' }),
),
],
};If a child component cannot find parent data and the parent has a path, the strategy is the first thing to check. The alternative is to walk up with route.parent?.data.
Common errors
- Key mismatch.
resolve: { product: ... }but the component readsdata['products']or declaresinput<Product>()nameditem. The result isundefined, or an input that never receives a value. - Missing
withComponentInputBinding(). Aninput.requiredthat is never set throws aNG0950error when read. If you see it on a routed component, checkprovideRouterfirst. - Treating the value as possibly pending. Resolved data is present at activation. Adding
@if (product())guards in the template hides the real bug, which is usually a wrong key. - Resolver returns a
RedirectCommand. The component is never created in that case, so the component code needs no handling for it. - Mutating the resolved object. The same object can be held by the router state. Copy it before editing it in a form.
Exercise
A detail page at /products/:id uses product = inject(ActivatedRoute).snapshot.data['product']. A "next product" link goes to /products/2 while the user is on /products/1. The URL changes, but the page still shows product 1. Why does this happen, and what is a fix that works with signals?
Show answer
The router reuses the same component instance because only the :id parameter changed. The resolver runs again and ActivatedRoute.data emits the new product, but the snapshot value was read once at construction and never updates. Fix it by reading data reactively: product = toSignal(route.data.pipe(map(d => d['product'] as Product)), { requireSync: true }), or enable withComponentInputBinding() and declare product = input.required<Product>().
Exercise
A resolver is registered as resolve: { item: itemResolver }, but the component declares product = input.required<Product>() and withComponentInputBinding() is enabled. What happens, and what two changes could fix it?
Show answer
No input named product receives a value, so reading product() throws because the required input was never set. Either rename the resolve key to product, or rename the input to item. You can also alias the input with input.required<Product>({ alias: 'item' }).