角度路由 - 捕获具有相同结尾的所有路径

时间:2018-04-13 13:07:40

标签: angular routing routes

我有一个场景,可以直接调用相同的组件,也可以从不同的其他组件调用。像这样:

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},
];

但它没有用。

儿童路线,参数或片段似乎不适合我的情况。

关于如何简化代码的任何想法?

1 个答案:

答案 0 :(得分:0)

您可以创建全局路线:

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));