Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular router: ignore slashes in path parameters

I have dynamic routes that could contain slashes or anti-slashes inside parameters , for example:

http://localhost:4200/dashboard/T64/27D I should navigate to a page with route T64/27D

Here's how I navigate this.router.navigate(['dashboard/'+this.groupListPage[0].code]); this.groupList[0].code contain T64/27D

Actually Angular separate T64 and 27D as 2 different pages.

Here's the error:

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'

How can I tell to Angular that / is a part of the param ?

like image 627
infodev Avatar asked Dec 11 '22 06:12

infodev


1 Answers

Assumming the route:

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

And :id can exist in {'abc','ab/c'}, in order to consider the inner '/' as part of the path, you need to use a custom 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;
};

A working example can be found in this blitz

like image 178
Jota.Toledo Avatar answered Dec 12 '22 18:12

Jota.Toledo