diff --git a/adev/src/content/guide/routing/data-fetching-with-resources.md b/adev/src/content/guide/routing/data-fetching-with-resources.md index 9c7c4c33a14..208290d1503 100644 --- a/adev/src/content/guide/routing/data-fetching-with-resources.md +++ b/adev/src/content/guide/routing/data-fetching-with-resources.md @@ -1,19 +1,19 @@ # Data fetching with resources -The Angular Router integrates with Angular Signals through the `resources` route configuration. This allows you to fetch data reactively using `Resource` APIs. +The Angular Router integrates with Angular signals through the `resources` route configuration. This allows you to fetch data reactively using `Resource` APIs. ## Why use route resources? Route resources offer several advantages over traditional [data resolvers](/guide/routing/data-resolvers): -- **Parallel execution**: Route resources run concurrently across all matched routes, eliminating the sequential waterfall delays of resolvers. +- **Parallel execution**: Route resources across all matched routes load concurrently instead of one route at a time. - **Non-blocking data loading**: Use `nonBlocking()` to activate the route immediately and render loading skeletons or UI states while data loads in the background. -- **Reload without renavigation**: Call `.reload()` on individual resources or update signal parameters to refresh data without triggering a full route navigation, rerun guards, or re-match routes. -- **Reactive data fetching**: Resources integrate directly with Angular Signals, automatically re-evaluating when signal dependencies change and exposing reactive status signals like `isLoading()` and `error()`. +- **Reload without renavigation**: Call `.reload()` on individual resources or update signal parameters to refresh data without rerunning guards or rematching routes. +- **Reactive data fetching**: Resources integrate directly with Angular signals, automatically re-evaluating when signal dependencies change and exposing reactive status signals like `isLoading()` and `error()`. -## Setup +## Enabling route resources -To enable this feature, provide `withRouterResources()` to your router configuration: +To enable route resources, provide `withRouterResources()` to your router configuration: ```ts import {provideRouter, withComponentInputBinding, withRouterResources} from '@angular/router'; @@ -23,9 +23,11 @@ bootstrapApplication(App, { }); ``` -You can then define resources in your `Route` definitions and access them directly as component inputs. +TIP: Enable `withComponentInputBinding()` so the router can bind resolved resources directly to component inputs. -The `resources` function runs in an injection context, allowing you to use `inject()` to access services, API clients, or stores directly inside the route definition. +## Defining route resources + +You define resources on a route with the `resources` function. The function runs in an injection context, so you can use `inject()` to access services, API clients, or stores directly inside the route definition. ```angular-ts import {Component, inject, input, resource} from '@angular/core'; @@ -52,28 +54,18 @@ const routes: Routes = [ template: `

User: {{ user().name }}

`, }) export class UserProfile { - // The router automatically binds only the value for blocking resources. + // The router binds only the value for blocking resources. user = input.required(); } ``` -TIP: Notice we map the exact primitive ID we need in `params: () => ctx.params()['id']`. Passing the entire parameters object (e.g. `params: () => ctx.params()`) can cause unnecessary resource reloads during navigations. Because the router generates a new object identity for the parameters on navigation, the resource will trigger a refetch even if the specific `id` value you care about hasn't changed. +### The `ResourceContext` object -### Parallel execution (avoiding waterfalls) +The `resources` function receives a `ResourceContext` that provides access to reactive route signals: `params`, `queryParams`, `fragment`, and `data`. -Traditional data resolvers execute sequentially from parent routes to child routes. If a parent route resolver takes 200ms and a child route resolver takes 300ms, the navigation is blocked for 500ms total. +### Supported resource implementations -In contrast, all route resources across the entire matched route hierarchy execute concurrently during navigation. In the same scenario, navigation completes in 300ms (the time of the slowest resource), eliminating network waterfalls. - -TIP: If a resource depends on data from another resource, you can compose the requests within a single resource's loader function, or chain dependent resources using [`chain()`](/guide/signals/resource#chaining-resources). - -### ResourceContext - -The `resources` function receives a `ResourceContext` providing access to reactive route signals, including path and matrix parameters through `params`, as well as `queryParams`, `fragment`, and `data`. - -### Resource implementations and async configuration - -The `resources` map supports any Angular `Resource` implementation (such as `resource()`, `rxResource()`, or custom resources). +The `resources` function can return any Angular `Resource` implementation, such as `resource()`, `rxResource()`, or a custom resource. ```ts import {Routes} from '@angular/router'; @@ -109,49 +101,37 @@ resources: async (ctx) => { }, ``` -## Reloading resources without renavigation +## Fine-grained change tracking with signals -With traditional data resolvers, refetching data requires triggering a route navigation (such as navigating with `onSameUrlNavigation: 'reload'`), which re-evaluates all route guards, resolvers, and route matching logic. +A resource tracks the signals that its `params` function reads. Read the exact value you need so that the resource refetches only when that value changes: -With route resources, you can reload data without renavigating: - -1. **Programmatic reload**: Call `.reload()` directly on the `Resource` instance. -2. **Reactive reload**: If a resource's `params` computation reads signals (such as an application filter or state signal), updating those signals automatically re-triggers the resource loader. - -When using `withComponentInputBinding()`, blocking resources bind only their unwrapped value directly to component inputs. If you need to interact with the underlying `Resource` instance (for example, to trigger a manual `.reload()` or inspect status signals), access it through `ActivatedRoute` or `ActivatedRouteSnapshot`: - -```angular-ts -import {Component, inject, input} from '@angular/core'; -import {ActivatedRoute} from '@angular/router'; - -@Component({ - template: ` -

User: {{ user().name }}

- - `, -}) -export class UserProfile { - user = input.required(); - private userResource = inject(ActivatedRoute).resources?.['user']; - - refreshUser() { - // Reloads only this specific resource without renavigating the route - this.userResource?.reload(); - } -} +```ts +resources: (ctx) => ({ + products: resource({ + // Tracks only the 'category' query parameter + params: () => ctx.queryParams()['category'], + loader: ({params: category}) => fetchProducts(category), + }), +}), ``` +A navigation that changes an unrelated query parameter, such as `?sort=desc` or `?page=2`, leaves `category` unchanged, so the resource does not refetch. + +TIP: Read specific properties, such as `ctx.params()['id']`, instead of returning an entire parameters object, such as `ctx.params()`. The router creates a new object on every navigation, so returning the whole object refetches the resource even when the individual values are unchanged. + +## Parallel execution + +Data resolvers execute sequentially from parent route to child route. If a parent route resolver takes 200ms and a child route resolver takes 300ms, the navigation is blocked for 500ms. + +Route resources across the matched route hierarchy run concurrently, so the same navigation completes in 300ms, the time of the slowest resource. + ## Blocking and non-blocking resources -By default, all resources returned from `resources` are **blocking**. The router waits until the data is fully loaded before activating the route and component. +By default, every resource returned from `resources` is blocking: the router waits until the data is fully loaded before it activates the route and the component. -**For blocking resources, the router binds only the resolved value to the component input.** The input type in your component is `T` instead of `Resource`. +For a blocking resource, the router binds the resolved value to the component input, so the input type is `T` instead of `Resource`. The component never observes a `loading` state because the router blocks navigation until the resource loads, and it never observes an `error` state because the router cancels the navigation when the resource errors. -This simplifies your component because it does not need to handle loading or error states. Because the router blocks navigation until the resource is loaded, the component never observes a `loading` state. If the resource throws an error, the router cancels the navigation, so the component never observes an `error` state. - -If you prefer to handle loading states in the UI, use the `nonBlocking()` wrapper utility. Non-blocking resources do not halt navigation. The router activates the component immediately, allowing the UI to handle loading or skeleton states. - -**For non-blocking resources, the router binds the full `Resource` object to the component input.** This allows you to access `.isLoading()`, `.error()`, and other resource signals in your component. +To handle loading states in the UI instead, wrap the resource in `nonBlocking()`. The router activates the component immediately and binds the full `Resource` object to the component input, which gives you access to `isLoading()`, `error()`, and the other resource signals. ```angular-ts import {Component, input, Resource, resource} from '@angular/core'; @@ -161,7 +141,7 @@ const routes: Routes = [ { path: 'reports', component: Reports, - resources: (ctx) => ({ + resources: () => ({ reportData: nonBlocking( resource({ loader: () => fetchHeavyReportData(), @@ -187,11 +167,11 @@ export class Reports { } ``` -NOTE: If a blocking resource throws an error, the router cancels the navigation and emits a `NavigationError` event. Resources wrapped in `nonBlocking()` that error will complete navigation and expose the error via the `resource.error()` signal. +NOTE: If a blocking resource errors, the router cancels the navigation and emits a `NavigationError` event. A resource wrapped in `nonBlocking()` completes the navigation and exposes the failure through its `error()` signal. ### Redirecting from a resource -If a blocking resource needs to redirect the user (for example, if an item is not found), throw a `RedirectCommand` inside the resource loader. The router will cancel the current navigation and redirect to the specified URL: +If a blocking resource needs to redirect the user (for example, if an item is not found), throw a `RedirectCommand` inside the resource loader. The router cancels the current navigation and redirects to the specified URL: ```ts import {inject, resource} from '@angular/core'; @@ -221,19 +201,49 @@ const routes: Routes = [ ]; ``` +## Reloading resources without renavigation + +With data resolvers, refetching data requires a route navigation (for example, navigating with `onSameUrlNavigation: 'reload'`), which rematches routes and reruns guards and resolvers. + +Route resources support two ways to refresh data in place: + +1. **Programmatic reload**: Call `.reload()` on the `Resource` instance. +2. **Reactive reload**: Update a signal that the resource's `params` function reads, such as an application filter or state signal, which reruns the loader. + +Because the router binds only the value of a blocking resource to a component input, read the `Resource` instance from `ActivatedRoute` or `ActivatedRouteSnapshot` when you need to call `.reload()` or inspect status signals: + +```angular-ts +import {Component, inject, input} from '@angular/core'; +import {ActivatedRoute} from '@angular/router'; + +@Component({ + template: ` +

User: {{ user().name }}

+ + `, +}) +export class UserProfile { + user = input.required(); + private userResource = inject(ActivatedRoute).resources?.['user']; + + refreshUser() { + // Reloads only this specific resource without renavigating the route + this.userResource?.reload(); + } +} +``` + ## Transitional states during pending navigations -When moving between views (or reloading the same view with new parameters), switching abruptly to a loading skeleton can create a jarring UI flash. +While a navigation is pending, the router freezes the resources that it exposes on `ActivatedRoute`, which masks intermediate `loading` and `reloading` states. -The router automatically masks intermediate `loading` and `reloading` states of resolved resources while a navigation is pending. +If you navigate from `/user/1` to `/user/2` and the router reuses the `UserProfile` component, the component keeps rendering the data from `/user/1` until `/user/2` resolves. The router then unfreezes the resources and the UI transitions directly to the new data with no loading flash. -If you navigate from `/user/1` to `/user/2`, `UserProfile` stays mounted and continues rendering data from `/user/1` (frozen in its exact state) until `/user/2` resolves. Once `/user/2` settles, the router unfreezes the UI, transitioning directly to the new data with no loading flash. - -NOTE: Route resources returned to the router are read-only. Manual `.reload()` calls attempted during an active navigation transition or rollback recovery return `false` to avoid interrupting router transition tracking. +The router exposes these resources as read-only, even when the `resources` function returns a writable resource such as `resource()`. You can read the resource signals and call `reload()`, but not `set()` or `update()`. A `reload()` call during an active navigation or during rollback recovery returns `false` so that it cannot interrupt the router's transition tracking. ### Rollback recovery on cancellation -If a navigation is cancelled (for example, by a guard), the router reverts the state tree to the previous state. This reversion can cause the resource's signal dependencies (such as route parameters) to revert to their previous values. +If a navigation is cancelled (for example, by a guard), the router reverts the state tree to the previous state. This reversion can cause the resource's signal dependencies, such as route parameters, to revert to their previous values. Because the parameters changed back, the resource might automatically trigger a new load to fetch data for the old parameters. To prevent flashing a loading state for data that was already visible, the router retains the previous resource snapshot in the UI until the resource has settled in the reverted state.