角度路由器处理路由器变量中的"/"




我一直在研究带有路由的 Angular 项目,所以让我们考虑下面这样的路线。

{
path : 'preview/:Id',
loadChildren : () => import('./path/preview/preview.module').then( m => m.PreviewModule),
}

因此,此route可能具有字母数字值,例如(a-zA-Z0-9(,也可以具有特殊字符(例如/(,由加密产生的哈希值.js如下所示。

preview/QQZnNw+VjBg/cAXvy6nxdiQ==

所以在上面的路线中,参数Id将具有像这个QQZnNw+VjBg/cAXvy6nxdiQ==这样的价值,这就是我试图实现的。

错误

但不幸的是,我收到错误,说明无法识别的路由,因为,上面的值在其路由中有"/"。

以前我尝试过的是,我尝试将/:Id(/[\S]+/g)这样的正则表达式添加到路由参数中,以便它可以接受此路由,

{
path : 'preview/:Id(/[\S]+/g)',
loadChildren : () => import('./path/preview/preview.module').then( m => m.PreviewModule),
}

拜托,谁能帮我找到办法。

您可以使用UrlMatcher.

function slashMatcher(path: string, param: string): UrlMatcher {
return (
segments: UrlSegment[],
group: UrlSegmentGroup,
route: Route
): UrlMatchResult => {
const { length } = segments;
const firstSegment = segments[0];
if (firstSegment.path === path && length >= 2) { // firstSegment.path == preview
const paramSegments = segments.slice(1);
const paramPaths = paramSegments.map(segment => segment.path); // ["QQZnNw+VjBg", "cAXvy6nxdiQ=="]
const mergedParam = paramPaths.join("/"); // QQZnNw+VjBg/cAXvy6nxdiQ==
const idSegment: UrlSegment = new UrlSegment(mergedParam, { [param]: mergedParam });
return { consumed: segments, posParams: { [param]: idSegment } };
}
return null;
};
}
const routes: Routes = [
{ 
matcher: slashMatcher('preview', 'Id'), 
loadChildren : () => import('./path/preview/preview.module').then( m => m.PreviewModule),
},
];
// In component
const id$ = this.route.paramMap.pipe(map(params => params.get('Id')));

多亏了这个答案,我找到了解决方法。

我创建了两个实用程序函数,用于在加密和解密该哈希代码时将"/">替换为一些哈希代码。

convertSpecial = (text: string) => {
const ciphertext = this.encrypt(text);
return ciphertext.replace(/+/g,'p1L2u3S').replace(///g,'s1L2a3S4h').replace(/=/g,'e1Q2u3A4l');
}
unconvertSpecial = (ciphertext: string) => {
ciphertext = ciphertext.toString().replace(/p1L2u3S/g, '+' ).replace(/s1L2a3S4h/g, '/').replace(/e1Q2u3A4l/g, '=');
const text = this.decrypt(ciphertext);
return text;
}

所以在重定向时,

<a href="#" [routerLink]="['/preview', convertSpecial(item?._id)]" > </a>

在安装组件时,

ngOnit()
{
this.Id = this.unconvertSpecial(this.Id);
}

最新更新