Angular 路由器:忽略路径参数中的斜杠

2024-04-07

我有动态路线could参数内包含斜杠或反斜杠,例如:

http://localhost:4200/dashboard/T64/27D我应该导航到带有路线的页面T64/27D

这是我的导航方式this.router.navigate(['dashboard/'+this.groupListPage[0].code]); this.groupList[0].code包含T64/27D

实际上角度是分开的T64 and 27D作为2个不同的页面。

这是错误:

ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'dashboard/T64/27D'
Error: Cannot match any routes. URL Segment: 'dashboard/T64/27D'

我怎样才能告诉 Angular/是参数的一部分?


假设路线:

{
    path: 'dashboard/:id',
    component: FooComponent
 }

并且 :id 可以存在于 {'abc','ab/c'} 中,为了将内部 '/' 视为路径的一部分,您需要使用自定义网址匹配器 https://angular.io/api/router/UrlMatcher:

const customMatcher: UrlMatcher = (
  segments: UrlSegment[],
  group: UrlSegmentGroup,
  route: Route
): UrlMatchResult => {
  const { length } = segments;
  const firstSegment = segments[0];
  if (firstSegment.path === "dashboard" && length === 2 || length === 3) {
    // candidate for match
    const idSegments = segments
      .slice(1); // skip prefix
    const idPaths = idSegments.map(segment => segment.path);
    const mergedId = idPaths.join('/');// merge the splitted Id back together
    const idSegment: UrlSegment = new UrlSegment(mergedId, { id: mergedId });
    return ({ consumed: segments, posParams: { id: idSegment } });
  }
  return null;
};

可以在此处找到一个工作示例blitz https://stackblitz.com/edit/ignore-slash?file=src%2Fapp%2Fapp.module.ts

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Angular 路由器:忽略路径参数中的斜杠 的相关文章

随机推荐