我有一个场景,可以直接调用同一个组件,也可以从不同的其他组件调用。像这样:
const appRoutes: Routes = [
{path: 'manufacturer', component: ManufacturerComponent},
{path: 'model/manufacturer', component: ManufacturerComponent},
{path: 'product/model/manufacturer', component: ManufacturerComponent},
{path: 'order/product/model/manufacturer', component: ManufacturerComponent},
];
我这样做是为了能够从流程中的任何步骤添加制造商。我使用的模型、产品和其他组件也是如此。
所有相关组件都在一个路由器插座中打开。
这缩放得非常糟糕,我最终在 appRoutes 数组中可能有 100 个对象。
我想我可以做这样的事情:
const appRoutes: Routes = [
{path: '**/manufacturer', component: ManufacturerComponent},
];
但它不起作用。
子路线、参数或片段似乎不适合我的情况。
关于如何简化代码的任何想法?
您可以创建一个全局路由:
export const manufacturer: Routes = [{
path: 'manufacturer', component: ManufacturerComponent
}];
并将其作为孩子分享到您的其他路线中(因为它是您路线的子路线(:
const appRoutes: Routes = [
{path: 'manufacturer', component: ManufacturerComponent},
{path: 'model', component: ManufacturerComponent, children: manufacturer},
// ... And other routes
];
如果您需要添加其他孩子,只需扩展您的路线:
const appRoutes: Routes = [
{path: 'manufacturer', component: ManufacturerComponent},
{path: 'model', component: ManufacturerComponent, children: [
// Other routes
...manufacturer
]},
// ... And other routes
];
编辑 如果您想添加到所有路线:
addManufacturerChild = route => {
if (route.children && route.children.length) {
for (let r of route.children) { addManufacturerChild(r); }
} else {
route.children = [];
}
route.children.push(...manufacturer);
};
export const appRoutes = [...].map(route => addManufacturerChild(route));