Angular 角度布线多条路径到同一组件

Angular 角度布线多条路径到同一组件,angular,Angular,有没有办法从这个角度优化代码 { path: 'access-requests', canActivate: [AccessGuard], component: AccessRequestsComponent, children: [ { path: '', redirectTo: 'today', pathMatch: 'full' }, { path: 'today', component:

有没有办法从这个角度优化代码

{
  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
    }
    ]
}
您可以使用该属性

{
路径:“访问请求”,
canActivate:[AccessGuard],
组件:AccessRequestsComponent,
儿童:[
{
路径:“”,
重定向至:“今天”,
路径匹配:“已满”
},
{
matcher:matcherFunction,
组件:AccessRequestsComponent
}
]
}

导出函数匹配函数(url:URLSEMENT[]){
如果(url.length==1){
const path=url[0]。路径;
if(path.startsWith('today'))
||path.startsWith('明天')
||path.startsWith('expired')){
返回{consumered:url};
}
}
返回null;
}

注意:未测试的代码

您可以使用映射数组:

儿童:[
//为了简洁起见,排除了其他路径
…[‘今天’、‘明天’、‘过期’].map(路径=>({
路径
组件:AccessRequestsComponent
}))
]

基于CornelC的答案,我编写了一个方法,该方法接受字符串数组作为路径,并输出一个url匹配器,该匹配器将匹配数组中的一个元素:

export const routingMatcher:((路径:string[])=>UrlMatcher)=(路径:string[])=>{
常量结果:UrlMatcher=(段)=>{
const matchingPathIndex=路径。findIndex((路径,索引)=>{
const pathSegments=path.split(“/”);
返回段。每个((段,i)=>
pathSegments.length>i&&(
pathSegments[i].startsWith(“:”)?true:segment.path.toLowerCase()==pathSegments[i].toLowerCase());
});
如果(匹配路径索引>=0){
const matchingPath=路径[matchingPathIndex];
消耗的常量:URLSEMENT[]=[];
常量参数={};
matchingPath.split(“/”).forEach((路径,i)=>{
消费推送(段[i]);
if(path.startsWith(“:”){
常量参数=路径子字符串(1);
params[param]=段[i];
}
});
返回{
消耗:消耗,
posParams:params
};
}
返回null;
};
返回结果;
};
您可以在路由定义中这样使用它:

儿童:[
//为了简洁起见,排除了其他路径
matcher:routingMatcher([“今天”、“明天”、“过期])
组件:AccessRequestsComponent
}))
]

可能是可以使用
regex
是的,可以使用这样的东西。我们可以看到如何进行路径匹配作为一个例子。我意识到以上可能是更好的实践,但这对我来说似乎更具可读性。@DaneBrouwer感谢您的反馈!关于“更好的实践”部分:虽然更通用,但url匹配器的方法更慢、更复杂,而且没有必要(因为在我们的例子中没有好处)。我认为K.I.S.S.是一个很好的实践老实说,我甚至没有想到使用自定义url匹配器的含义——我只是觉得它更像角度。然而,我不能与K.I.S.S.或性能优化争论!请注意,此方法将导致Angular在不同路径之间切换时重新加载组件,这可能是您想要的,也可能不是您想要的。对我来说,它显示了错误:
error error:Uncaught(承诺中):TypeError:无法读取未定义类型的属性“split”错误:无法读取defaultUrlMatcher(router.js:525)上未定义类型的属性“split”
我正在使用v9。