比如这个路由器
{
path: '/client',
component: ClientRootComponent,
children: [
{path: '', component: ClientListComponent},
{path: ':clientId', component: ClientOpenComponent, resolve: makeResolver(ClientOpenResolver)}
]
},
{
path: '**',
component: NotFoundComponent
}
会将两个 URL /client/1234 和 /client/asdf 传递给 ClientOpenComponent。我如何才能使 /client/asdf 匹配为 NotFound 并传递给 NotFoundComponent?
最佳答案
您可以将自定义匹配器传递给您的路由
import { defaultUrlMatcher } from '@angular/router/src/shared';
function digitsMatcher(segments: UrlSegment[], segmentGroup: UrlSegmentGroup, route: Route): UrlMatchResult | null {
const result = defaultUrlMatcher(segments, segmentGroup, route);
if (!result || !result.consumed || result.consumed.length < 1) {
return;
}
const re = /^\d+$/;
const match = re.exec(result.consumed[0].path);
if (match) {
return result;
}
return null;
}
{
path: '/client',
component: ClientRootComponent,
children: [
{path: '', component: ClientListComponent},
{path: ':clientId', component: ClientOpenComponent, resolve: makeResolver(ClientOpenResolver), matcher: digitsMatcher}
]
},
{
path: '**',
component: NotFoundComponent
}
代码未经测试
另见
关于angular - 仅当参数为Angular2中的整数时如何匹配路由?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41543298/