// component
export class HeroComponent {
constructor(private activatedRoute: ActivatedRoute) {}
ngOnInit() {
this.activatedRoute.data.subscribe(({ hero }) => {
// do something with your resolved data ...
})
// or
this.hero = this.activatedRoute.data['hero']
}
}
// resolve
@Injectable({ providedIn: 'root' })
export class HeroResolver implements Resolve<Hero> {
constructor(private service: HeroService) {}
resolve(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<Hero>|Promise<Hero>|Hero {
return this.service.getHero(route.paramMap.get('id')).pipe(
catchError(error => of('No data'))
);
}
}
// rota
@NgModule({
imports: [
RouterModule.forRoot([
{
path: 'detail/:id',
component: HeroDetailComponent,
resolve: {
hero: HeroResolver
}
}
])
],
exports: [RouterModule]
})
export class AppRoutingModule {}
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter