使用自定义匹配
问题描述:
限制路线,我有以下的路由配置:使用自定义匹配
const routes: Routes = [
{
component: MyComponent,
path: '',
children: [
{
component: MyListComponent,
path: ''
},
{
component: MyFormComponent,
path: ':id/edit'
},
{ path: '**', redirectTo: '' }
]
}
];
为了限制参数为数字,我开始寻找,花toooooooooo多的时间之后,我发现这个办法关闭(不知道为什么)问题:https://github.com/angular/angular/issues/12442
于是,我改变了我的配置(especifically的事项的部分)以下:
{
component: MyFormComponent,
matcher: ComplexUrlMatcher('id', /[1-9]+\/edit/)
}
export function ComplexUrlMatcher(paramName: string, regex: RegExp) {
return (
segments: UrlSegment[],
segmentGroup: UrlSegmentGroup,
route: Route) => {
const parts = [regex];
const posParams: { [key: string]: UrlSegment } = {};
const consumed: UrlSegment[] = [];
let currentIndex = 0;
for (let i = 0; i < parts.length; ++i) {
if (currentIndex >= segments.length) {
return null;
}
const current = segments[currentIndex];
const part = parts[i];
if (!part.test(current.path)) {
return null;
}
posParams[paramName] = current;
consumed.push(current);
currentIndex++;
}
if (route.pathMatch === 'full' &&
(segmentGroup.hasChildren() || currentIndex < segments.length)) {
return null;
}
return { consumed, posParams };
}
}
来源:https://gist.github.com/matanshukry/22fae5dba9c307baf0f364a9c9f7c115
它几乎工作。如果我去一个像这样的路线:
my_path/1
...它的工作原理,但我要的是:
my_path/1/edit
我怎样才能解决这个功能,使其工作?
答
您需要在您的路由器中继续嵌套子组件,以使该功能立即可用。下面用路由器第4版。我的作品,这将只允许ID参数是一个或多个数字和操作参数来匹配确切的词“编辑”:
const routes: Routes = [
{
component: MyComponent,
path: '',
children: [
{
component: MyListComponent,
path: ''
},
{
matcher: ComplexUrlMatcher("id", /[0-9]+/),
component: MyFormComponent,
{
matcher: ComplexUrlMatcher("action", /(edit)/),
component: MyFormEditComponent,
}
},
{ path: '**', redirectTo: '' }
]
}
];
如果使用子组件不为你工作,你将不得不重写一些正则表达式逻辑来满足你的需求。