- 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
- 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);
}
}
@NgModule({
imports: [
RouterModule.forRoot([
{
path: 'team/:id',
component: TeamComponent,
resolve: {
team: TeamResolver
}
}
])
],
providers: [TeamResolver]
})
class AppModule {}
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 { }
class TeamComponent implements OnInit {
private team: Team;
constructor(private route: ActivatedRoute) {}
ngOnInit() {
this.team = this.route.data;
}
}