是否有一些我应该编写的中间件可以检索与作为 URL 参数提供的 ID 对应的 Car,然后将其交给 CarDetailComponent,因此所述组件永远不需要对 Car 对象本身发出请求?
我相信您正在寻找的是route-resolver。在路由时,解析器可以拦截 URL 参数,使用它来获取对象,并使其可用于在该路由下呈现的所有组件。例如...
应用程序路由.module.ts
{
path: 'widgets',
component: WidgetsComponent,
},
{
path: 'widgets/:id',
resolve: { widget: WidgetResolver },
children: [
{ path: '', redirectTo: 'details', pathMatch: 'prefix' },
{
path: 'details',
component: WidgetDetailsComponent,
},
{ path: 'edit', component: WidgetFormComponent }
]
},
小部件.resolver.ts
@Injectable()
export class WidgetResolver implements Resolve<Widget> {
constructor(private service: WidgetService) { }
resolve(route: ActivatedRouteSnapshot): Observable<any> {
return this.service.getById(parseInt(route.paramMap.get('id') || ''))
.pipe(first()); // must complete to resolve route
}
}
小部件详细信息.component.ts
@Component({
selector: 'app-widget-details',
templateUrl: './widget-details.component.html',
styleUrls: ['./widget-details.component.scss'],
})
export class WidgetDetailsComponent {
widget$ = this.route.data.pipe(
pluck('widget')
);
constructor(
private route: ActivatedRoute
) { }
}