Angular 2从URL中删除哈希(#)

jor*_*ang 55 html5 typescript angular

我试图从Angular 2中的网址中删除#符号,但我找不到任何关于如何删除它而没有产生任何问题的良好解释.

我记得AngularJS 1更容易添加 $locationProvider.html5Mode(true);

如果你能告诉我这是一个好习惯(删除#)还是可能影响应用程序的SEO(或改进它),我将不胜感激.

PS:我正在使用带有打字稿的Angular 2

Sei*_*vic 86

正如@Volodymyr Bilyachat指出的那样,它PathLocationStrategy是Angular2 中的默认位置策略,如果#它存在于url中,那么它必须在某处被覆盖.

在模块提供程序旁边,检查您的模块导入,也可以通过提供以下{ useHash: true }的第二个参数来覆盖它RouterModule.forRoot:

imports: [
    ...
    RouterModule.forRoot(routes, { useHash: true })  // remove second argument
]
Run Code Online (Sandbox Code Playgroud)

另请注意,在使用时,PathLocationStrategy您需要将Web服务器配置index.html为所有请求的位置(app的入口点).

  • 这解决了#removal的问题,但是当我们刷新页面或h5时,这不起作用. (6认同)
  • 伙计们,在ng build --prod这个解决方案不起作用,给出404错误..有什么线索? (2认同)
  • @HydTechie,JinnaBalu,当使用PathLocationStrategy(HTML5路由)时,您需要配置您的Web服务器以为所有请求的URL提供index.html文件(应用程序的入口点). (2认同)

Vol*_*hat 31

角度有位置策略

查看app.module.ts,其中app已自动引导

@NgModule({
.......
  providers: [
....
    { provide: LocationStrategy, useClass: HashLocationStrategy },
....
]
});
Run Code Online (Sandbox Code Playgroud)

并删除此部分,因为PathLocationStrategy是默认策略


pra*_*jha 20

上面的答案有关于从URL中删除哈希的正确解释,但是当您更改LocationStrategy后端时会受到影响,因为后端无法理解您的所有Angular 2路由.以下是使用后端支持删除哈希的步骤.

1)更改Angular以使用PathLocationStrategy

@NgModule({
  .....
  providers: [
    // Below line is optional as default LocationStrategy is PathLocationStrategy
    {provide: LocationStrategy, useClass: PathLocationStrategy} 
  ]
})
Run Code Online (Sandbox Code Playgroud)

2)更改index.html中的基础Href,Angular2将处理基于Href的所有路径

<base href="/app-context/">
Run Code Online (Sandbox Code Playgroud)

例如

<base href="/app/">
Run Code Online (Sandbox Code Playgroud)

3)在后端服务器上,我们必须为任何带有以下模式的请求呈现index.html文件

"/app/**" - Render index.html for any request coming with "/app/**" pattern
Run Code Online (Sandbox Code Playgroud)

的index.html

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>My App</title>
    <base href="/app/">
  </head>
  <body>
    <app-root>Loading...</app-root>
    <script type="text/javascript" src="vendor.bundle.js"></script>
    <script type="text/javascript" src="main.bundle.js"></script>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

  • 你能简要解释一下“/app-context/”吗? (2认同)