Angular 15 项目。我的所有组件都是独立的,并且我没有 App.Module。目前,我的所有路由都已在我的 main.ts 中配置和引导。
给出以下工作场景。
/dashboard > 重定向至 /dashboard/games
/dashboard/games > 加载 GamesComponent
我正在尝试实现以下路径,
/dashboard/games/game/123 > 加载 GameComponent
在我的路由中,游戏是仪表板的子路由。而游戏是游戏的子路线。
但是,当我尝试加载路径 /dashboard/games/game/123 时,它会加载 GamesComponent
这是我的路由的相关部分,
const routes: Routes = [{
path: 'dashboard',
loadComponent: () => import('./app/user-dashboard/user-dashboard.component').then((m) => m.UserDashboardComponent),
canActivate: [AuthGuard],
children: [
{
path: '',
redirectTo: 'games',
pathMatch: 'full'
},
{
path: 'games',
loadComponent: () => import('./app/user-dashboard/games/games.component').then((m) => m.GamesComponent),
children: [
{
path: 'game/:id',
loadComponent: () => import('./app/user-dashboard/games/game/game.component').then((m) => m.GameComponent)
}
]
}
]
}};
bootstrapApplication(AppComponent,
{
providers: [
importProvidersFrom(RouterModule.forRoot(routes, { enableTracing: true }))
]
})
任何人都可以帮助我理解我在这里缺少什么吗?
如果我将路由 game/:id 从游戏的子级中删除,并将其添加到同一级别,转换为 games/game/:id 那么它就可以工作。那么为什么这条子路线行不通呢?
这是一种不幸的预期行为......
这样做对于延迟加载的组件是无效的,因为您正在尝试定义尚未加载的组件的路由子级:
{
path: 'games',
loadComponent: () => import('./app/user-dashboard/games/games.component').then((m) => m.GamesComponent),
children: [
{
path: 'game/:id',
loadComponent: () => import('./app/user-dashboard/games/game/game.component').then((m) => m.GameComponent)
}
]
}
要使其工作,您需要在组件内定义“游戏”路由子级
app/user-dashboard/games/games.component
;
或者如您所想,将路线重新配置为:
{
path: 'games',
loadComponent: () => import('./app/user-dashboard/games/games.component').then((m) => m.GamesComponent),
},
{
path: 'games/game/:id',
loadComponent: () => import('./app/user-dashboard/games/game/game.component').then((m) => m.GameComponent)
}