Lab 09: Resolver
π Resourcesβ
π Starter Codeβ
step-9-album-wholesale-v16-deactivate-guard
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β
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β
Add resolver to route configuration:
const routes: Routes = [
{
path: 'albums/edit/:id',
component: AlbumEditComponent,
resolve: { album: albumResolver }
}
];
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);
}
}
}