resolve 서비스를 이용하면 라우팅할 때 데이터를 미리 불러올 수 있다.
// resolve.service.ts
@Injectable({
providedIn: 'root'
})
export class ResolveService implements Resolve<any> {
constructor(
private service: AppService
) {
}
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): any {
return this.service.getData().pipe(
mergeMap((res: HttpResponse<any>) => {
if (res.body) {
return of(res.body);
} else {
return EMPTY;
}
})
);
}
}
// app.module.ts
@NgModule({
...
imports: [
...
RouterModule.forRoot([
{
path: '',
component: ChildComponent,
resolve: {
resolveData: ResolveService
}
}
])
],
...
})
// component.ts
this.activatedRoute.data.subscribe(res => {
console.log(res);
});