Angular 子路由可在没有父路由的情况下导航

Angular Child Routes Navigable without Parent Route

我在 Angular 13 应用程序中有一些路由加载了包含许多子路由的其他模块。

我的路由设置在各个模块中:

@NgModule({
    declarations: [DashboardComponent],
    imports: [RouterModule.forChild(childRoutes)]})
export class ChildModule{}

export const childRoutes = [
    {path: 'dashboard', component: DashboardComponent},
    {path: 'reports', component: ReportsComponent}];

我的父模块延迟加载子模块:

export const appRoutes = [
    {path: 'store', component: StoreLayoutComponent,
     loadChildren: () => import('app/store/child.module').then(m => m.ChildModule)}];

@NgModule({
    imports: [
    ...
    RouterModule.forRoot(appRoutes)
    ],
    ...})
export class AppModule {}

urls https://localhost:4200/store/dashboardhttps://localhost:4200/dashboard 加载子项 DashboardComponent.

第二个 url 应该无效。为什么有效?

尝试将 child 路由放在 children.

Child

@NgModule({
    declarations: [DashboardComponent],
    imports: [RouterModule.forChild(childRoutes)]})
export class ChildModule{}

export const childRoutes = [{
children:[
    {path: 'dashboard', component: DashboardComponent},
    {path: 'reports', component: ReportsComponent}]
}];

Parent

export const appRoutes = [
    {path: 'store', component: StoreLayoutComponent,
     loadChildren: () => import('app/store/child.module').then(m => m.ChildModule)}];

@NgModule({
    imports: [
    ...
    RouterModule.forRoot(appRoutes)
    ],
    ...})

这里的问题是 StoreModule 被延迟加载并出现在应用程序的 app.module.ts 中。这为模块创建了路由,既作为 app.module 的直接子模块,也作为正确地址的延迟加载模块。

app.module.ts 的导入语句中删除 StoreModule 的声明解决了问题。

希望这对以后的人有所帮助。