javascript / intermediate
Snippet
Route Resolvers for Data Pre-fetching
Resolvers allow you to fetch data before a route is activated. This prevents the component from loading in an incomplete state (e.g., without data) and improves the user experience by avoiding 'flickering' while waiting for async requests.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
export const heroResolver: ResolveFn<Hero> = (route: ActivatedRouteSnapshot) => {const id = route.paramMap.get('id')!;return inject(HeroService).getHero(id);};// In app.routes.ts{path: 'hero/:id',component: HeroComponent,resolve: { hero: heroResolver }}
angular
Breakdown
1
export const heroResolver: ResolveFn<Hero>
Defines a functional resolver that returns an Observable, Promise, or literal value.
2
resolve: { hero: heroResolver }
Maps the resolver output to the 'hero' key in the route's data object.