angular 路由 children 基于可变段

angular route children based on variable segments

我有一个指向相同位置的 url 模式,但它以不同的数据结尾。

示例:

请记住,"detail" 和 "object" 都是动态的,例如:detail1-category、detail2-category、detail3-category、object1、object2、objectt3。

URL1 = /url/detail-category

URL2 = /url/object

我需要根据 URL 是否以“-category”结尾来加载 Children,我使用的是匹配器,但由于无法使用匹配器和路径,我丢失了 "path" 变量同时

原文:

{ path: 'url/:id',  
    loadChildren: './modules/child.module#ChildModule'
},

已更新:

{ matcher: categoriesMatcher, 
    loadChildren: './modules/child.module#ChildModule'
},

export function categoriesMatcher(url: UrlSegment[]) {
    return url.length === 1 && url[0].path.endsWith('-category') ? ({consumed: url, path: url}) : null;
  }

// 以上部分取自此处,它有效,但我们丢失了指示组件行为的数据。 Angular 2 different components with same route

匹配器可以提供参数作为匹配逻辑的一部分。 return 值应包含一个 posParam 属性 以及每个路由参数的值。

例如:

export function MyAwesomeMatcher ( url: UrlSegment[] ): UrlMatchResult {
    if (url.length === 0) {
        return null;
    }
    const reg = /^(awesome-path)$/;
    const param = url[ 0 ].toString();
    if (param.match( reg )) {
       // myValue: "awesome-path"
       return ({ consumed: url, posParams: { myValue: url[ 0 ] } });
   }
   return null;
}

// define application routes.
const routes: Routes = [
   { path: '', component: HomeComponent, pathMatch: 'full' },
   { matcher: MyAwesomeMatcher, component: MyAwesomeComponent }
   ...
];

从此处复制的上述示例代码:

https://gist.github.com/anein/fba647b4206695d109c30e1fc0d2e8ee