Reputation: 165
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?
Upvotes: 4
Views: 15013
Reputation: 631
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']
}
Upvotes: 1
Reputation: 4166
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 {}
Upvotes: 7
Reputation: 694
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
Upvotes: 3