删除 URL Angular 11 中的哈希 (#)

Remove hash(#) in URL Angular 11

我想去掉URL中的#,但是去掉之后部署到服务器上就会出现问题。当页面刷新时,将获得 404 状态。

示例

https://一个/用户/(有效)

https://a/user/1(不工作)

app-routing.module.ts

    @NgModule({
  imports: [RouterModule.forRoot(routes)],
  providers: [
    {provide: LocationStrategy, useClass: PathLocationStrategy} 
  ],
  exports: [RouterModule]
})

app.module.ts

......
providers: [ Location, {provide: LocationStrategy, useClass: PathLocationStrategy}]

请指教我该怎么做。

PathLocationStrategy 是 Angular 路由的默认定位策略,它应该可以解决您的散列 (#) 问题。

您的代码没有错误,请仔细检查以下几点

  1. RouterModule.forRoot(routes, { useHash: true }) //use Hash should not be there
  2. 供应商:[ // 下面一行是可选的,因为默认 LocationStrategy 是 PathLocationStrategy {provide: LocationStrategy, useClass: PathLocationStrategy} ]

如果您仅在部署时在服务器中遇到问题,请检查服务器中的入口点配置。应该是index.html个文件。

注意:当使用 PathLocationStrategy 时,您需要配置您的 Web 服务器,以便为所有请求的位置提供 index.html(应用程序的入口点)。

同时检查index.html中的<base href="/">,在后端服务器,我们必须根据路径渲染index.html文件。