重定向后网址不会更改

  • 本文关键字:重定向 angular
  • 更新时间 :
  • 英文 :


正如标题所说,我没有重定向到默认直接的组件。当我尝试访问localhost:4200时,它永远不会导航到localhost:4200/workbenchappRoutingModule:

const routes: Routes = [
{path:'', redirectTo:'/workbench', pathMatch:'full'},
{path:'**', component:PageNotFoundComponent}
];

homeRoutingModule:

const routes: Routes = [
{
path:'',
component:HomeComponent,
children:[
{path:'workbench',component:WorkbenchComponent},
]
}
];

应用程序。Moudule:

imports: [
...
HomeModule,
AccountModule,
AppRoutingModule,
],

有人有这样的经验,知道如何解决它吗?谢谢你!

正确的路由方式如下:

AppModule:

@NgModule({
imports: [
...,
AppRoutingModule
]
})
export class AppModule { ... }

AppRoutingModule:

const routes: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent, children: homeRoutingRoutes },
{ path: '**', component: PageNotFoundComponent
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export 

HomeRoutingModule

export const homeRoutingRoutes: Routes = [
{ path: '', redirectTo: 'workbench', pathMatch: 'full' },
{ path:'workbench', component: WorkbenchComponent }
]

那么在原始代码和这个之间是什么不起作用呢?

AppRoutingModule中没有注册的path: 'workbench'。如果没有注册路径,Angular会一直把导航推送到path: '**'路由。

如果你想直接重定向到path: 'workbench,你需要在AppRoutingModule中声明它,而不是在child下,如:

AppRoutingModule:

const routes: Routes = [
{ path: '', redirectTo: 'workspace', pathMatch: 'full' },
{ path: 'workbench', component: WorkbenchComponent },
{ path: '**', component: PageNotFoundComponent
];

注意,这样做意味着home组件不需要了。

添加到子路由

const routes: Routes = [
{
path:'',
component:HomeComponent,
children:[
{path:'workbench',component:WorkbenchComponent},
{path:'', redirectTo:'/workbench', pathMatch:'full'},
{path:'**', component:PageNotFoundComponent}
]
}
];

虽然这不是我喜欢的,但我解决了这个问题,为home功能模块添加了一个路径,如下所示:

const routes: Routes = [
{
path:'home',
component:HomeComponent,
canActivate:[authGuard],
children:[
{path:'workbench',component:WorkbenchComponent},
]
}
];
并重定向到
{path:'', redirectTo:'/home/workbench', pathMatch:'full'},

它最终工作到localhost:4200/home/workbench。如果有人有更好的方法使重定向路由更短到localhost:4200/workbench,请分享。

最新更新