【问题标题】:Angular 6 routing works with ng serve, not Visual StudioAngular 6 路由适用于 ng serve,而不是 Visual Studio
【发布时间】:2018-12-12 01:42:34
【问题描述】:

我觉得这是一个愚蠢的问题,但我是 Angular 新手,在任何地方都找不到答案...

我正在尝试在新的 Angular 6 应用中设置路由。当我使用 ng serve 从命令行提供服务时,我可以很好地路由到一个组件,但当我从 Visual Studio 提供服务时则不行。这只是基本的路由。

app-routing.module.ts 中定义的路由:

const routes: Routes = [
  { path: '', component: MaintenanceComponent },
  { path: 'merchants', component: MaintenanceComponent }  
];

app.component.html 中的路由器出口标签:

<div style="text-align:center">
  <h1>
    Welcome to {{ title }}!
  </h1>
</div>
<router-outlet></router-outlet>

有趣的是,我可以看出路由器在 VS 中运行时正在识别对根的请求,因为它将返回 404 而没有 { path: '', component: MaintenanceComponent }。但是,无论如何尝试访问 /merchants 都会返回 404。所以这是一个线索。

我缺少什么简单的东西?

该项目使用 .NET Core Web API。

【问题讨论】:

    标签: angular visual-studio asp.net-web-api angular-ui-router


    【解决方案1】:

    这是因为当客户端向 /merchants 发出请求时,服务器需要返回 index.html 才能启动角度路由。方法是通过添加到 web.config 来重写 IIS URL:

    <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="/" />
          </rule>
        </rules>
      </rewrite>
    </system.webServer>
    

    这告诉iis将所有不是有效文件或目录的请求重写到/ url

    【讨论】:

    • 谢谢!是的,我正在慢慢整理,并认为我有类似的解决方案。我会在这里发布。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-12
    • 1970-01-01
    • 2019-01-09
    • 2019-08-09
    • 2018-12-27
    • 2019-03-21
    • 1970-01-01
    相关资源
    最近更新 更多