我有以下路由器配置:
@NgModule({
imports: [
RouterModule.forChild([
{ path: 'office', component: OfficePage},
{ path: 'office/:category1/', component: OfficeInnerPage},
{ path: 'office/:category1/:category2', component: OfficeInnerPage},
{ path: 'office/:category1/:category2/:category3', component: OfficeInnerPage},
{ path: 'office/:category1/:id', component: DetailPage}
])
],
})
OfficeInerPage
- 项目列表控制器
DetailPage
- 详情项目控制器
:id
示例 os10198
网址示例
http://example.com/office/business_center/subway/
http://example.com/office/business_center/subway/arbat
http://example.com/office/business_center/os10198
问题
Angular路由器状态:category1/:category2/
重写:category1/:id
状态。我怎样才能解决这个问题?
答案 0 :(得分:1)
您需要添加额外的路径名,例如:
{path: 'office/:category1/item/:id', component: DetailPage}
否则angular无法知道您是要转到:category2
还是:id
,而且因为您的数组中有:id
作为最后一项,它会否决第一个一个
答案 1 :(得分:1)
我找到了解决方案。
路由器中的某处(source code)。我找到了属性matcher
,它是一个Function
,允许你自己处理路径。
在我的情况下,我写下以下功能:
function pathMatcher(segments: UrlSegment[], group: UrlSegmentGroup, route: Route) {
if (segments.length > 2) {
if(segments[2].path.match(/([\w|]+[\d]+)/)) {
let posParams = {'id': segments[2]};
return {consumed: segments, posParams: posParams};
} else {
return null;
}
} else {
return null;
}
}
我的路由器配置:
@NgModule({
imports: [
RouterModule.forChild([
{path: 'office', component: OfficePage},
{path: 'office/:category1', component: OfficeInnerPage},
{path: 'office/:category1/:category2/:category3', component: OfficeInnerPage},
{path: 'office/:category1/:category2/:category3/:category4', component: OfficeInnerPage},
{matcher: <any>pathMatcher, component: DetailPage}, // <- here is matcher, also its conflicts with path property
{path: 'office/:category1/:category2', component: OfficeInnerPage}, // it should be below state with matcher
])
],
})
现在我解决了这些类型的链接:
http://example.com/office/business_center/subway/ http://example.com/office/business_center/os10198
P.S。有用的gist