Angular 在路由中使用 loadchildren 时,5 个子路由在根级路由器出口加载

Angular 5 child route getting loaded at root Level router-outlet when using loadchildren in routing

我有一个带有路由器出口的根应用程序组件,并且路由是从 home 模块路由加载的,该模块路由在其子路由中使用 loadchildren 进行延迟加载。 home 组件中有一个 router-outlet,并且 home 的所有子模块中都有一个 router-outlet,它们是延迟加载的。路由工作正常,但子路由也在根路由器出口中加载。 例如:- 组件 'testCreateComponent' 正在加载 localhost:4200/test/create 以及 localhost:4200/create。

示例代码级别如下:-

app.component.html

<div>app</div>
<router-outlet></router-outlet>

app-routing.module.ts

export const APP_ROUTES: Routes = [
    {path: '**', redirectTo: '', pathMatch: 'full'}
];

home.component.html

<div>home</div>
<router-outlet><router-outlet>

首页-routing.module.ts

const routes: Routes = [{
  path: '',
  component: HomeComponent,
  canActivate: [LoggedUserGuard],
  canActivateChild: [AuthGuard],
  children: [
    {path: '', redirectTo: 'dashboard', pathMatch: 'full'},
    {
      path: 'test',
      loadChildren: () => testModule
    },
    {
      path: 'dashboard',
      component: DashboardComponent,
      data: {
        breadcrumb: 'Dashboard'
      }
    },
    {
      path: 'dummy',
      loadChildren: () => dummyModule,
    }
  ]
}];

testComponent.html

<div>Test</test>
<router-outlet></router-outlet>

测试-routing.module.ts

const routes: Routes = [{
  path: '',
  component: TestComponent,
  children: [
    {path: '', component: ListComponent,
      data: {
        breadcrumb: 'List'
      }},
    {path: 'create', component: testCreateComponent},
    { path: 'detail/:id',
      component: TestEditComponent,
    }
  ]
}];

问题可能出在您导入延迟加载模块的方式上。

我们在延迟加载的模块中遇到了类似的问题,这些模块被错误地导入 explicitly/eagerly 以及模块文件顶部的 TypeScript 导入部分(而不是仅在 loadChildren 中内联功能)。

为了在一个巨大的项目中轻松找到它们,我想我们用 preloadingStrategy: PreloadAllModules 配置了路由器,注销了 router.config,并检查了路由及其组件。从模块顶部的 TypeScript 导入部分删除导入(并且只保留它们内联)解决了这个问题。

尝试删除

import { testModule } from "./path/to/file/containing/test.module";

从你的文件的顶部开始,而不是在路线中只使用以下内容

loadChildren: () => import("./path/to/file/containing/test.module").then((m) => m.testModule)

另请查看 Angular Docs: Troubleshooting lazy-loading modules