Search code examples
angularroutesangular-routing

Add variable prefix to angular routing


I am trying to update an old BackBone.js app to Angular (4/5). One of the requirements is to keep using the old routes in this new app, which triggers some challenges.

The old routes are build as follows:

site.com/r/{username}/{route}

e.g.

site.com/r/johndoe/homepage
site.com/r/janedoe/blog

I'm now using Angular routing without hash, but every route i build in Angular now consists of a long string:

{ path: '/r/:username/homepage' }

I'm hoping there is a cleaner way to uses routes in here. The :username variable is only needed when bootstrapping the app, so it would be a lot nicer to strip the first bit off of the Url and start NG route paths after this.

I know base href will compile the app to a potential subdirectory, but this will not work with the variable username.

Is there a way to make this work in Angular?


Solution

  • You can do something like this:

    const appRoutes: Routes = [
     {
       path: 'r',
       component: AppComponent,
       children: [
          { path: ':username/homepage', component: HomePageComponent },
          // other children or you can use loadChildren
       ]
     }
    ];
    

    https://angular.io/guide/router#lazy-loading-route-configuration