Lab 09: Resolver
📖 Resources
Section titled “📖 Resources”🚀 Starter Code
Section titled “🚀 Starter Code”step-5-album-wholesale-v16-post-add-custom-async-validator
Continue from your Lab 08 result. If you need a fresh copy, use step-5-album-wholesale-v16-post-add-custom-async-validator as your base and complete Labs 05–08 first.
In this lab, you’ll use a route resolver to pre-fetch album data before navigating to the edit page. You’ll create a functional resolver that loads data from the service, configure it in the route definition, and access the resolved data in your component.
📝 Instructions
Section titled “📝 Instructions”Step 1: Create Resolver
Section titled “Step 1: Create Resolver”Create a functional resolver:
import { ResolveFn } from '@angular/router';import { inject } from '@angular/core';
export const albumResolver: ResolveFn<Album | null> = (route, state) => { const albumService = inject(AlbumService); const id = Number(route.paramMap.get('id'));
return albumService.getAlbumById(id).pipe( catchError(() => of(null)) );};Step 2: Add to Route
Section titled “Step 2: Add to Route”Add resolver to route configuration:
const routes: Routes = [ { path: 'albums/edit/:id', component: AlbumEditComponent, resolve: { album: albumResolver } }];Step 3: Access Resolved Data
Section titled “Step 3: Access Resolved Data”Get data in component:
export class AlbumEditComponent implements OnInit { private route = inject(ActivatedRoute);
ngOnInit() { const album = this.route.snapshot.data['album'] as Album; if (album) { this.albumForm.patchValue(album); } }}
