【问题标题】:Can't access Angular Components via URL无法通过 URL 访问 Angular 组件
【发布时间】:2019-10-31 12:18:50
【问题描述】:

我制作了一个 Angular 应用程序,它应该位于 .NET 应用程序之上。有一个 ASP.Net-Application 的 Index-View,我应该从中调用某个 Angular-View。

为了测试,我尝试使用 http serve 在本地托管应用程序 - 在这里我只能访问 index.html(在我的情况下没有条目) - 像 /users 这样的路由去用户概览会导致404。

这是我的路由模块:

const routes: Routes = [
  {path: 'users', component: UsersComponent},
  {path: 'user/new', component: UserNewComponent},
  {path: 'user/edit/:id', component: UserEditComponent}
];

@NgModule({
  declarations: [],
  imports: [
    CommonModule,
    RouterModule.forRoot(routes)
  ],
  exports: [RouterModule]
})
export class AppRoutingModule { }

我知道它应该是一个单页应用程序——但现在,对于那个迭代,它应该是这样的。我该如何解决这个问题?

【问题讨论】:

  • 你是否构建了 Angular 应用程序来生成 index.html @FlixRo
  • 如果我查看 /dist 文件夹,它就在那里 - 所以我猜是的
  • 真的有必要将 angular-application 连接到 asp.net 应用程序中吗?我想到了一个类似分离的前端和后端的东西,我通过路由访问前端

标签: html angular routing


【解决方案1】:
RouterModule.forRoot(routes, { useHash: true }) 

app.routing 文件中尝试useHash: true。 这对我有用。

【讨论】:

  • 对于 index.html 以外的任何其他路由仍然获得404
  • 你能用routerlink访问组件吗?如果是,那么这可能是本地主机上的问题,只有这将在部署后在服务器上工作。
【解决方案2】:

解决方案是为 IIS 和 URL-Rewriter 2 添加一个带有明确重写规则的 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>

【讨论】:

    【解决方案3】:

    您需要一个将所有路由重定向到index.html 的服务器。 http serve 不会那样做。

    在内部,Angular 使用称为虚拟路由的东西来处理路由。

    例如:

    在 Node.js 中,我们有类似的东西,

    app.get('*', function (req, res) {
      res.sendFile(path.join(frontend_path, 'index.html'));
    });
    

    出于开发目的,您可以使用以下方式运行本地服务器,

    ng serve

    在顶级 Angular 目录中

    【讨论】:

    • 有什么方法可以简单地测试它吗?
    • 在存在package.json @FlixRo 的角度文件夹中使用ng serve
    • 但这是正常的开发方式,对吧?因为当通过 ng serve 启动它并在 webpack-dev-server 上运行时,它就像一个魅力——应用程序默认在 localhost:4200 监听。因此它可以毫无问题地工作。但如果我构建它,它就不起作用。
    • 确切地说,对于生产,您需要一个服务器将所有传入路由重定向到 index.html 或使用反向代理来路由这些请求。
    • 但是,如果 Asp.NET-Application 调用 /users 以链接到该视图但又被重新路由到索引,我该如何实现我的预期行为?还是我错过了什么?
    猜你喜欢
    • 2019-07-11
    • 2020-08-05
    • 2016-04-28
    • 1970-01-01
    • 2021-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-07
    相关资源
    最近更新 更多