Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forward Slash in Angular Route Parameters

How do I set up my routes so that my parameter can take forward slashes?

For example: myapp.com/file/rootfolder/subfolder/myfile

This doesn't work:

const SECTION_ROUTES: Routes = [
    { path: 'file/:path', component: FileStoreComponent }
];

Is having / in routing parameter values possible?

I've read about URL approaches that use URL encoding. However, I'd like my user to be able to type the URL.

like image 373
Jonas Arcangel Avatar asked Jun 28 '17 19:06

Jonas Arcangel


1 Answers

To achieve this with a recent version of Angular (9.X for me), you can use the Route.matcher parameter. Here is an example:

function filepathMatcher(segments: UrlSegment[], 
                         group: UrlSegmentGroup, 
                         route: Route) : UrlMatchResult {
  // match urls like "/files/:filepath" where filepath can contain '/'
  if (segments.length > 0) {
    // if first segment is 'files', then concat all the next segments into a single one
    // and return it as a parameter named 'filepath'
    if (segments[0].path == "files") {
      return {
        consumed: segments,
        posParams: {
          filepath: new UrlSegment(segments.slice(1).join("/"), {})
        }
      };
    }
  }
  return null;
}

const routes: Routes = [
  { path: 'login', component: LoginComponent },
  { matcher: filepathMatcher, component: FilesComponent },
  // ...
];

@NgModule({
  imports: [RouterModule.forRoot(routes, { useHash: true })],
  exports: [RouterModule]
})
export class AppRoutingModule { }

You will be able to access the parameter in your Component through the ActivatedRoute.paramMap

Note the query parameters are also working and preserved.

However, you will still have issues if the URL contains parenthesis, for example /files/hello(world:12)/test because they are interpreted by angular as auxiliary routes

In this case, you can add a custom UrlSerializer to encode parenthesis and you'll have to decode them in your Component.

like image 164
Thibaut A. Avatar answered Nov 03 '22 07:11

Thibaut A.