Angular Resolver & Child Routing - Tuong-Nguyen/Angular-D3-Cometd GitHub Wiki

Resolver

  • Interface that class can implement to be a data provider.
  • Resolver will add data to the route so that the component will get data from route instead of service.
    • Resolver depends on service

How To Use

  • Create a service that fetch data from server.
// mock service
class Backend {
  fetchTeam(id: string) {
    return 'someTeam';
  }
}
  • Create a class resolver that implements Resolve<T>, T is model class or interface
    • Decorate with @Injectatble()
    • Override resolve function
@Injectable()
class TeamResolver implements Resolve<Team> {
  constructor(private backend: Backend) {}
 
  resolve(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<any>|Promise<any>|any {
    return this.backend.fetchTeam(route.params.id);
  }
}
  • Apply resolver to Module
@NgModule({
  imports: [
    RouterModule.forRoot([
      {
        path: 'team/:id',
        component: TeamComponent,
        resolve: {
          team: TeamResolver
        }
      }
    ])
  ],
  providers: [TeamResolver]
})
class AppModule {}

Child Routing

  • Create a child routing
export const teamRouting = RouterModule.forChild([
      {
        path: 'team/:id',
        component: TeamComponent,
        resolve: {
          team: TeamResolver
        }
      }
    ]);
  • Use child routing and apply resolver to child module
@NgModule({
  imports: [
    teamRouting
  ],
  declarations: [  
  ],
  exports: [
    TeamComponent
  ],
  providers: [ TeamResolver ]
})
export class TeamModule { }
  • Get data from the route
class TeamComponent implements OnInit {
   private team: Team;
   constructor(private route: ActivatedRoute) {}
   ngOnInit() {
      this.team = this.route.data;
   }
}
⚠️ **GitHub.com Fallback** ⚠️