https://angular.io/api/router/Resolve
You can use route resolver in angular to make API call to retreive some data then return as observable, then you can capture this observable in destination component mapped to route to process this data.
Description
The following example implements a resolve() method that retrieves the data needed to activate the requested route.
@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'));
}
}Here, the defined resolve() function is provided as part of the Route object in the router configuration:
@NgModule({
imports: [
RouterModule.forRoot([
{
path: 'detail/:id',
component: HeroDetailComponent,
resolve: {
hero: HeroResolver
}
}
])
],
exports: [RouterModule]
})
export class AppRoutingModule {}And you can access to your resolved data from HeroComponent:
@Component({
selector: "app-hero",
templateUrl: "hero.component.html",
})
export class HeroComponent {
constructor(private activatedRoute: ActivatedRoute) {}
ngOnInit() {
this.activatedRoute.data.subscribe(({ hero }) => {
// do something with your resolved data ...
})
}
}
No comments:
Post a Comment