Resolve Exemplo

PHOTO EMBED

Thu Dec 29 2022 02:42:35 GMT+0000 (Coordinated Universal Time)

Saved by @ilivanilton #angular #rxjs-pattern

// 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 {}
content_copyCOPY

https://angular.io/api/router/Resolve