为 angular 路由添加变量前缀
Add variable prefix to angular routing
我正在尝试将旧的 BackBone.js 应用更新为 Angular (4/5)。
其中一项要求是在这个新应用中继续使用旧路由,这会引发一些挑战。
旧路由构建如下:
site.com/r/{username}/{route}
例如
site.com/r/johndoe/homepage
site.com/r/janedoe/blog
我现在正在使用 Angular 没有散列的路由,但是我在 Angular 中构建的每条路由现在都包含一个长字符串:
{ path: '/r/:username/homepage' }
我希望这里有更简洁的方法来使用路由。
:username 变量仅在引导应用程序时才需要,因此最好去掉 Url 的第一位并在此之后启动 NG 路由路径。
我知道 base href 会将应用程序编译到潜在的子目录,但这不适用于变量用户名。
有没有办法在 Angular 中完成这项工作?
你可以这样做:
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
或者你也可以这样做,它真的很简短,也应该这样做
https://angular.io/api/common/APP_BASE_HREF
用法:
@NgModule({
providers: [{provide: APP_BASE_HREF, useValue: '/my/app'}]
})
class AppModule {}
对我来说,基础 URL 会根据使用我们软件的客户而改变。
这篇文章非常适合我的解决方案:https://medium.com/@anandshende1994/setting-base-href-dynamically-in-angular-6-b7fe824848cf
在index.html
<script>
window['base-href'] = window.location.pathname;
console.log(window['base-href']);
</script>
在 app.module.ts(提供商部分)中:
{
provide: APP_BASE_HREF,
useValue: window['base-href']
}
我正在尝试将旧的 BackBone.js 应用更新为 Angular (4/5)。 其中一项要求是在这个新应用中继续使用旧路由,这会引发一些挑战。
旧路由构建如下:
site.com/r/{username}/{route}
例如
site.com/r/johndoe/homepage
site.com/r/janedoe/blog
我现在正在使用 Angular 没有散列的路由,但是我在 Angular 中构建的每条路由现在都包含一个长字符串:
{ path: '/r/:username/homepage' }
我希望这里有更简洁的方法来使用路由。 :username 变量仅在引导应用程序时才需要,因此最好去掉 Url 的第一位并在此之后启动 NG 路由路径。
我知道 base href 会将应用程序编译到潜在的子目录,但这不适用于变量用户名。
有没有办法在 Angular 中完成这项工作?
你可以这样做:
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
或者你也可以这样做,它真的很简短,也应该这样做
https://angular.io/api/common/APP_BASE_HREF
用法:
@NgModule({
providers: [{provide: APP_BASE_HREF, useValue: '/my/app'}]
})
class AppModule {}
对我来说,基础 URL 会根据使用我们软件的客户而改变。
这篇文章非常适合我的解决方案:https://medium.com/@anandshende1994/setting-base-href-dynamically-in-angular-6-b7fe824848cf
在index.html
<script>
window['base-href'] = window.location.pathname;
console.log(window['base-href']);
</script>
在 app.module.ts(提供商部分)中:
{
provide: APP_BASE_HREF,
useValue: window['base-href']
}