首页 > 解决方案 > Angular Router usehash:导航不保留hastag之前的url

问题描述

我有以下网址:

https://localhost:4200/example/#/

当我没有像以下示例所示那样导航其他角度路线时,/example将从 URL 中删除。生成的 URLhttps://localhost:4200/#/firstSegment/secondSegment不是https://localhost:4200/example/#/firstSegment/secondSegment

...
constructor(private router: Router) {}
....

navigate() {
    this.router.navigate([`/firstSegment/secondSegment`]);
}

有一种方法可以在#每次执行导航之前保留 URL 部分?

遵循我的路由器配置:

@NgModule({
   .....
   imports: [
      .....
      RouterModule.forRoot(
      appRoutes,
      {
        enableTracing: false, // <-- debugging purposes only
        useHash: true,
        initialNavigation: false
      }
     .....
   ]

})

标签: javascriptangulartypescriptangular-router

解决方案


对于默认路由,您需要将前缀设置为angular.json

...
"projects": {
    "app-name": {
      "prefix": "example",
    ...
}
...

更多细节 https://angular.io/guide/workspace-config


推荐阅读