【问题标题】:Angular2 without hash in the urlAngular2在url中没有哈希
【发布时间】:2017-05-30 11:04:30
【问题描述】:

现在,我的网站 url 看起来像这样,因为我使用的是 here 描述的方法

http://localhost:4200/#/cadastro

是否可以删除url中的hash而不出现404错误?

编辑:添加了路由器模块

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

export const routing = RouterModule.forRoot(appRoutes);

【问题讨论】:

    标签: html angular angular2-routing


    【解决方案1】:

    如果您使用的是 Angular final,哈希的原因可能是:

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

    因此,删除它可能会有所帮助。

    RouterModule.forRoot(yourRoutesHere)
    

    或者,如果您在您的提供程序中(在 NgModule 中)使用过:

    {provide: LocationStrategy, useClass: HashLocationStrategy}
    

    删除它。

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

    {provide: LocationStrategy, useClass: PathLocationStrategy}
    

    更多关于 LocationStrategy here

    现在我也看到了关于 404 问题的路线,您可以尝试更改以下内容

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

    到:

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

    更多关于路由here

    还要检查您的index.html 中是否设置了basehref,如下所示:

    <base href="/">
    

    【讨论】:

    • 已经是这样的“RouterModule.forRoot(yourRoutesHere)”。如果我删除“{provide: LocationStrategy, useClass:HashLocationStrategy}”,我会在重新加载页面时收到 404 错误。
    • 更新答案,试试PathLocationStrategy
    • 没有幸运 PathLocationStrategy,重新加载页面时仍然出现 404 错误:(
    • 好的,那么您的路线似乎有问题。您能否将您的路由模块添加到您的问题中?
    • 添加路由模块
    【解决方案2】:

    如果您使用 PathLocationStrategy 描述 here,您可以删除 URL 中的哈希。

    但是摆脱 404 错误需要一些服务器端调整。一种快速简单的方法是配置您的服务器以在请求任何http://yourhost/* 形式的 URL 时加载主页。

    【讨论】:

    • 是否打算将两个链接都指向同一页面?
    • 我不想使用 useHash。那我该如何解决这个问题
    【解决方案3】:

    创建一个 .htaccess 文件将以下代码粘贴到您的产品服务器上并上传。

    RewriteEngine On
    RewriteBase /
    RewriteRule ^index\.html$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.html [L]
    

    【讨论】:

    • 这实际上是一个非常好的答案。这对我帮助很大。但是我没有使用第一条规则。有必要吗?
    • 这取决于您使用的语言!以上代码适用于 Angular 9
    猜你喜欢
    • 2014-09-08
    • 2013-01-19
    • 2016-08-08
    • 1970-01-01
    • 1970-01-01
    • 2017-06-30
    • 2015-06-18
    • 2022-10-23
    • 2018-09-14
    相关资源
    最近更新 更多