为角度路由添加变量前缀

时间:2017-11-16 14:08:32

标签: angular routing angular-routing

我正在尝试将旧的BackBone.js应用更新为Angular(4/5)。 其中一个要求是在这个新应用程序中继续使用旧路由,这会引发一些挑战。

旧路线的构建如下:

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

e.g。

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

我现在使用没有哈希的Angular路由,但我在Angular中构建的每个路由现在都包含一个长字符串:

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

我希望在这里有更清洁的方式来使用路线。 :只有在引导应用程序时才需要:username变量,因此在此之后剥离Url的第一位并启动NG路径路径会更好。

我知道base href会将应用程序编译到一个潜在的子目录,但这不适用于变量username。

有没有办法在Angular中使这个工作?

3 个答案:

答案 0 :(得分:1)

您可以这样做:

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 :(得分:0)

或者您可以这样做,这确实很简短,应该做同样的事情

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

用法:

@NgModule({
  providers: [{provide: APP_BASE_HREF, useValue: '/my/app'}]
})
class AppModule {}

答案 2 :(得分:0)

对我来说,基本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']
  }
相关问题