简体   繁体   English

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

[英]Remove hash(#) in URL Angular 11

I want to remove the # from the URL, but when I remove it, there will be a problem when I deploy it to the server.我想把URL中的#去掉,但是去掉的时候,部署到服务器上就会出现问题。 When the page is refreshed, will get a status of 404.当页面刷新时,将获得 404 状态。

example例子

https: // a / user / (works) https://一个/用户/(作品)

https: // a / user / 1 (Not working) https://一个/用户/1(不工作)

app-routing.module.ts应用程序路由.module.ts

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

app.module.ts app.module.ts

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

Please advise me what should I do.请告诉我我该怎么做。

PathLocationStrategy is the default location strategy of Angular Routing, It should work and resolve your hash(#) problem. PathLocationStrategy 是 Angular Routing 的默认定位策略,它应该可以解决你的 hash(#) 问题。

There is no error in your code, double check below points您的代码中没有错误,请仔细检查以下几点

  1. RouterModule.forRoot(routes, { useHash: true }) //use Hash should not be there
  2. providers: [ // Below line is optional as default LocationStrategy is PathLocationStrategy {provide: LocationStrategy, useClass: PathLocationStrategy} ] providers: [ // 下面的行是可选的,因为默认 LocationStrategy 是 PathLocationStrategy {provide: LocationStrategy, useClass: PathLocationStrategy} ]

If you are only facing issue in server when deployed, Please check the entry point configuration in the server.如果您在部署时仅在服务器中遇到问题,请检查服务器中的入口点配置。 It should be index.html file.它应该是 index.html 文件。

NOTE : when using PathLocationStrategy you need to configure your web server to serve index.html (app's entry point) for all requested locations.注意:使用 PathLocationStrategy 时,您需要配置您的 web 服务器为所有请求的位置提供 index.html(应用程序的入口点)。

Also check the <base href="/"> in index.html and at the backend server, we must render the index.html file according to path.还要检查 index.html 中的<base href="/"> ,在后端服务器上,我们必须根据路径渲染 index.html 文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM