Can't access Angular Components via URL

二次信任 提交于 2020-03-25 19:11:30

问题


I've made an Angular Application which should sit on top of an .NET-Application. There is an Index-View of the ASP.Net-Application from which I should call a certain Angular-View.

For testing I tried locally host the application with http serve - here I can only access the index.html(which in my case has no entries) - a route like /usersto go to the User-Overview leads to an 404.

Here is my Routing-Module:

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 { }

I know that it should be an Single-Page-Application - but right now, for that iteration it should be like that. How can I solve this?


回答1:


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

Try useHash: true in app.routing file. This works for me.




回答2:


You'll need a server that redirects all the routes to index.html. http serve wont do that.

Internally, Angular handles the routes by use of something called virtual routes.

For Example:

In Node.js we have something like,

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

For development purposes, you could run a local server using,

ng serve

In top-level Angular Directory




回答3:


The solution was to add an web.config with explicit re-writing rules for IIS aswell as URL-Rewriter 2.

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>


来源:https://stackoverflow.com/questions/58643221/cant-access-angular-components-via-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!