有没有办法从此
优化此代码{
path: 'access-requests',
canActivate: [AccessGuard],
component: AccessRequestsComponent,
children: [
{
path: '',
redirectTo: 'today',
pathMatch: 'full'
},
{
path: 'today',
component: AccessRequestsComponent
},
{
path: 'tomorrow',
component: AccessRequestsComponent
},
{
path: 'expired',
component: AccessRequestsComponent
}
]
}
这样的事情
{
path: 'access-requests',
canActivate: [AccessGuard],
component: AccessRequestsComponent,
children: [
{
path: '',
redirectTo: 'today',
pathMatch: 'full'
},
{
path: 'today | tomorrow | expired',
component: AccessRequestsComponent
}
]
}
答案 0 :(得分:9)
您可以使用UrlMatcher属性。
{
path: 'access-requests',
canActivate: [AccessGuard],
component: AccessRequestsComponent,
children: [
{
path: '',
redirectTo: 'today',
pathMatch: 'full'
},
{
matcher: matcherFunction,
component: AccessRequestsComponent
}
]
}
和
export function matcherFunction(url: UrlSegment[]) {
if (url.length == 1) {
const path = url[0].path;
if(path.startsWith('today')
|| path.startsWith('tomorrow')
|| path.startsWith('expired')){
return {consumed: url};
}
}
return null;
}
注意:未经测试的代码
答案 1 :(得分:8)
您可以使用映射数组:
children: [
// excluding the other paths for brevity
...['today', 'tomorrow', 'expired'].map(path => ({
path,
component: AccessRequestsComponent
}))
]
答案 2 :(得分:0)
基于CornelC的答案,我编写了一种方法,该方法接受字符串数组作为路径并吐出将与数组元素匹配的url匹配器:
export const routingMatcher: ((paths: string[]) => UrlMatcher) = (paths: string[]) => {
const result: UrlMatcher = (segments) => {
const matchingPathIndex = paths.findIndex((path, index) => {
const pathSegments = path.split("/");
return segments.every((segment, i) =>
pathSegments.length > i && (
pathSegments[i].startsWith(":") ? true : segment.path.toLowerCase() === pathSegments[i].toLowerCase()));
});
if (matchingPathIndex >= 0) {
const matchingPath = paths[matchingPathIndex];
const consumed: UrlSegment[] = [];
const params = {};
matchingPath.split("/").forEach((path, i) => {
consumed.push(segments[i]);
if (path.startsWith(":")) {
const param = path.substring(1);
params[param] = segments[i];
}
});
return {
consumed: consumed,
posParams: params
};
}
return null;
};
return result;
};
您可以在路由定义中像这样使用它:
children: [
// excluding the other paths for brevity
matcher: routingMatcher(['today', 'tomorrow', 'expired'])
component: AccessRequestsComponent
}))
]