我正在一个项目中使用 Angular 4。我对 Angular 没有太多经验,我应该修复一个错误。我认为这很简单,但是当我加载应用程序并获取
/home
路线时,如果我单击刷新按钮,另一个 /home
会附加到 URL。
我的
RouterModule
配置如下所示:
RouterModule.forRoot([
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
/* other paths mapping to components */
{ path: '**', redirectTo: 'home' }
])
对于新手有什么想法吗?
我无法在 StackBlitz 中重现这一点。下面的 gif 显示了您的配置如何按我的预期工作:
请
enableTracing
并发布结果,以便我可以为您提供更多帮助:
RouterModule.forRoot(
appRoutes,
{ enableTracing: true } // <-- insert this here
)
一种解决方案是使用绝对重定向 (
redirectTo: '/home'
)。然而,正如 Viktor Savkin 在他的博客文章中所说:
本地重定向将单个 URL 段替换为不同的 URL 段。绝对重定向替换整个 URL。
但是当您在此处使用本地重定向(例如
redirectTo: 'home'
)时,应该再次将当前路径“home”替换为“home”,而不是附加它。此错误仅在生产中发生还是在开发中也发生?
您需要从使用字符串更改为使用组件名称
RouterModule.forRoot([
{ path: '', redirectTo: HomeComponent , pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
/* other paths mapping to components */
{ path: '**', redirectTo: 'home' }
])
正如@Tom提到的,这对我来说有效
<!-- index.html -->
<base href="" /> that caused this. I changed it to <base href="/" />
// app-routing.module.ts
RouterModule.forRoot([
{ path: '', redirectTo: 'home', pathMatch: 'full' },
/* other paths mapping to components */
])