不带哈希的Angular2 URL

11

现在,我的网站URL看起来像这样,因为我正在使用这里描述的方法。

http://localhost:4200/#/cadastro

是否可能删除URL中的哈希符号而不产生404错误?

编辑:添加了路由器模块

const appRoutes: Routes = [
    { path: '', component: HomeComponent },
    { path: 'cadastro', component: CadastroNoivosComponent },
    { path: '**', component: HomeComponent }
];

export const routing = RouterModule.forRoot(appRoutes);
3个回答

36

如果你正在使用Angular final,哈希的原因可能是以下之一:

RouterModule.forRoot(yourRoutesHere, { useHash: true })

因此,通过去除那个可能会有所帮助。

RouterModule.forRoot(yourRoutesHere)

另外,如果您在提供程序中(在NgModule中)使用了以下内容:

{provide: LocationStrategy, useClass: HashLocationStrategy}

只需移除那个。

如果您需要 LocationStrategy,请尝试将 HashLocationStrategy 更改为 PathLocationStrategy

{provide: LocationStrategy, useClass: PathLocationStrategy}

关于 LocationStrategy 的更多信息,请点击这里

现在我已经看到了您的路由以及有关404问题的信息,您可以尝试更改以下内容

{ path: '**', component: HomeComponent }

至:

{ path: '**', redirectTo: '', pathMatch: 'full' }

关于路由的更多信息,请点击这里

同时请确认在你的index.html文件中已经正确设置了basehref:

<base href="/">

2
已经是这样的了 "RouterModule.forRoot(yourRoutesHere)"。如果我删除"{provide: LocationStrategy, useClass: HashLocationStrategy}",当我重新加载页面时会得到404错误。 - Emilio Weba
更新的答案,尝试使用 PathLocationStrategy - AT82
使用PathLocationStrategy仍然没有成功,重新加载页面时仍然出现404错误 :( - Emilio Weba
在我的情况下,它在本地(ng serve)环境中工作,但在生产环境(ng build --aot --prod)中不起作用。 - Nilesh Mistry
@EmilioWeba,我也遇到了同样的问题,你找到任何解决方案了吗? - Nimatullah Razmjo
显示剩余3条评论

9
如果您使用PathLocationStrategy,如此处所述here,则可以删除URL中的哈希标记。
但是,要摆脱404错误需要进行一些服务器端调整。一种快速简便的方法是配置您的服务器在请求任何形式为http://yourhost/*的URL时加载主页。

这是打算将两个链接指向同一页吗? - Juan José Ramírez
我不想使用 useHash。那么我该如何解决这个问题? - Velusamy Venkatraman

4
创建一个 .htaccess 文件,粘贴以下代码并上传到您的生产服务器。
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]

这实际上是一个非常好的答案。它帮助了我很多。不过我没有使用第一条规则。这是必要的吗? - Radu Ionescu
取决于您使用的语言!上面的代码是用于Angular 9的。 - Sanchit

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接