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

时间:2017-01-17 01:11:16

标签: html5 angular typescript

我正在尝试从Angular 2中的网址中删除#符号,但我找不到有关如何删除它而不会产生任何问题的任何好的解释。

我记得在AngularJS 1上添加$locationProvider.html5Mode(true);

更容易

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

PS:我正在使用Angular 2 with typescript

3 个答案:

答案 0 :(得分:77)

正如@Volodymyr Bilyachat指出的那样,PathLocationStrategy是Angular2中的默认location strategy,如果网址中存在#,那么它必须被覆盖某处。

除了模块提供者,检查您的模块导入,也可以通过提供{ useHash: true }作为RouterModule.forRoot的第二个参数来覆盖它:

imports: [
    ...
    RouterModule.forRoot(routes, { useHash: true })  // remove second argument
]

另请注意,使用PathLocationStrategy时,您需要将网络服务器配置为为所有请求的位置提供index.html(应用的入口点)。

答案 1 :(得分:27)

角度为location strategy

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

#include <ctype.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>

#define LENGTH 45

int hash(char word[LENGTH+1]);

int main(void)
{
char word[LENGTH+1];
strcpy(word, "HelloWorld");

    //print out hash
    int hash = hash(word);
    // = ( ( (int) word[1] * (int) word[2]) % 1000 ); 

    printf("%i\n", hash);

return 0;
} 

int hash(char word[LENGTH+1])
{
int hash  = ( ( (int) word[1] * (int) word[2]) % 1000 );
return hash;
}

并删除此部分,因为PathLocationStrategy为default strategy

答案 2 :(得分:17)

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

1)更改Angular以使用PathLocationStrategy

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

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

<base href="/app-context/">

例如

<base href="/app/">

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

"/app/**" - Render index.html for any request coming with "/app/**" pattern

的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>
相关问题