Angular 4从url中删除哈希(#)

问题描述 投票:1回答:2

我的app.module.ts

@NgModule({
.......
  providers: [
....
    { provide: LocationStrategy, useClass: HashLocationStrategy},
....
]
});

当我删除这部分时,它可以在我的localhost中工作但是在进行了构建或ng构建--prod之后,当我刷新页面或h5时它不起作用。它给出了404错误。我想从我的网址中删除哈希(#)。有解决方案吗

angular angular4-router
2个回答
10
投票

你可以检查the angular guide about deployment

我们来谈谈HashLocationStrategyPathLocationStrategy之间的区别。欲了解更多信息,check the docs

默认情况下,Angular使用PathLocationStrategy

假设您的申请中有以下路线。

const routes: Route[] = [{
   path: '',
   redirectTo: 'home',
   pathMatch: 'full'
},
{
   path: 'home',
   component: HomeComponent
}];

当您路由到此组件时,您的地址栏将显示为localhost:4200/home。如果你使用HashLocationStrategy,它看起来像localhost:4200/#home。那么,这有什么区别?

  • PathLocationStrategy 当你在页面Home并点击F5按钮或刷新页面时,浏览器将向localhost:4200/home发出请求,这将由angular-cli处理,你将返回你的HomeComponent
  • HashLocationStrategy 同样,当你点击F5时,浏览器这次会向localhost:4200发出请求,因为它忽略了#之后发生的任何事情。

如果您不想拥有#,请删除您指出的部分。它默认是PathLocationStrategy。但是,当您在angular-cli之外运行应用程序时,这会让我们分开,这意味着从某个服务器构建和提供它。假设您使用ng build构建应用程序,并且您拥有缩小的已编译的javascript文件。您将它部署到运行在yourdomain.com上的某个服务器上

此外,您将这个构建的捆绑角度应用程序放在某个URL上,以便人们可以从yourdomain.com/ng-app访问您的应用程序,这里的一切都很好。甚至,当你路线到HomeComponent,它会工作,你的地址栏看起来像yourdomain.com/ng-app/home。但是,当您在此时点击F5时,您的浏览器将向yourdomain.com/ng-app/home发出请求,因为您从/ng-app为您的应用程序提供服务。您必须在服务器端进行一些配置,以便您可以提供以/ng-app/**开头的所有内容。

例如,我的s​​pring应用程序有这个方法返回角度应用程序,

@GetMapping("/ng-app/**") 

因此,当我的服务器获得以/ng-app开头的请求时,它只是将它传递给角度应用程序,它将处理正确的路由。

希望,这为你澄清它。


0
投票

您应该重写URL规则。因为每个服务器规则都不同,您可以尝试使用IIS。

=>在src文件夹中创建web.config并复制到代码下面。

        <?xml version="1.0" encoding="utf-8"?>
        <configuration>

        <system.webServer>
          <rewrite>
            <rules>
              <rule name="Angular Routes" stopProcessing="true">
                <match url=".*" />
                <conditions logicalGrouping="MatchAll">
                  <add input="{REQUEST_FILENAME}" matchType="IsFile" 
                     negate="true" />
                  <add input="{REQUEST_FILENAME}" matchType="IsDirectory" 
                    negate="true" />
                </conditions>
                <action type="Rewrite" url="./index.html" />
              </rule>
            </rules>
          </rewrite>
        </system.webServer>

        </configuration>

=>将role.config路径添加到angular-cli.json文件:

    "assets": [
        "assets",
        "favicon.ico",
        "web.config"
    ],

=>让我们构建:build --prod

© www.soinside.com 2019 - 2024. All rights reserved.