4

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?

3 Answers 3

8

Or you can do this, it is really brief, and should do the same

https://angular.io/api/common/APP_BASE_HREF

usage:

@NgModule({
  providers: [{provide: APP_BASE_HREF, useValue: '/my/app'}]
})
class AppModule {}
Sign up to request clarification or add additional context in comments.

Comments

3

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

1 Comment

Thank you, this seems like a better approach. Since i only want to use the :username when bootstrapping the app, i came up with this: { path: 'r/:username', component: AppComponent, children: [ { path: 'homepage', component: HomePageComponent' } ] }
1

For me, the base URL would change based on the client using our software.

This article was perfect for my solution: https://medium.com/@anandshende1994/setting-base-href-dynamically-in-angular-6-b7fe824848cf

In index.html

<script>
  window['base-href'] = window.location.pathname;
  console.log(window['base-href']);
</script>

In app.module.ts (providers section):

  {
    provide: APP_BASE_HREF,
    useValue: window['base-href']
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.