无法通过 URL 访问 Angular 组件
Can't access Angular Components via URL
我制作了一个 Angular 应用程序,它应该位于 .NET 应用程序之上。 ASP.Net-应用程序有一个索引视图,我应该从中调用某个 Angular-视图。
为了测试,我尝试使用 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 { }
我知道它应该是一个单页应用程序 - 但现在,对于那个迭代它应该是这样的。我该如何解决这个问题?
RouterModule.forRoot(routes, { useHash: true })
在 app.routing
文件中尝试 useHash: true
。
这对我有用。
您需要一个服务器将所有路由重定向到 index.html
。 http serve
不会那样做。
在内部,Angular 通过使用称为虚拟路由的东西来处理路由。
例如:
在Node.js中我们有类似的东西,
app.get('*', function (req, res) {
res.sendFile(path.join(frontend_path, 'index.html'));
});
出于开发目的,您可以运行本地服务器使用,
ng serve
在顶级 Angular 目录中
解决方案是为 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>
我制作了一个 Angular 应用程序,它应该位于 .NET 应用程序之上。 ASP.Net-应用程序有一个索引视图,我应该从中调用某个 Angular-视图。
为了测试,我尝试使用 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 { }
我知道它应该是一个单页应用程序 - 但现在,对于那个迭代它应该是这样的。我该如何解决这个问题?
RouterModule.forRoot(routes, { useHash: true })
在 app.routing
文件中尝试 useHash: true
。
这对我有用。
您需要一个服务器将所有路由重定向到 index.html
。 http serve
不会那样做。
在内部,Angular 通过使用称为虚拟路由的东西来处理路由。
例如:
在Node.js中我们有类似的东西,
app.get('*', function (req, res) {
res.sendFile(path.join(frontend_path, 'index.html'));
});
出于开发目的,您可以运行本地服务器使用,
ng serve
在顶级 Angular 目录中
解决方案是为 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>