Resolvers

A class that implements the Resolve interface (or a function with the same signature as the resolve() method) that you use to produce or retrieve data that is needed before navigation to a requested route can be completed.

Resolvers run after all route guards for a route tree have been executed and have succeeded. See an example of using a resolve guard to retrieve dynamic data.

Resolve

Interface that classes can implement to be a data provider. A data provider class can be used with the router to resolve data during navigation. The interface defines a resolve() method that is invoked when the navigation starts. The router waits for the data to be resolved before the route is finally activated.

Description

The following example implements a resolve() the method that retrieves the data needed to activate the requested route.

content_copy@Injectable({ providedIn: 'root' })
export class HeroResolver implements Resolve<Hero> {
  constructor(private service: HeroService) {}

  resolve(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<any>|Promise<any>|any {
    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:

content_copy@NgModule({
  imports: [
    RouterModule.forRoot([
      {
        path: 'detail/:id',
        component: HeroDetailComponent,
        resolve: {
          hero: HeroResolver
        }
      }
    ])
  ],
  exports: [RouterModule]
})
export class AppRoutingModule {}

You can alternatively provide an in-line function with the resolve() signature:

content_copyexport const myHero: Hero = {
  // ...
}

@NgModule({
  imports: [
    RouterModule.forRoot([
      {
        path: 'detail/:id',
        component: HeroComponent,
        resolve: {
          hero: 'heroResolver'
        }
      }
    ])
  ],
  providers: [
    {
      provide: 'heroResolver',
      useValue: (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => myHero
    }
  ]
})
export class AppModule {}

Last updated