Angular,如何在一个惰性加载的模块中包含多个组件?

Angular, how to include multiple components in a lazy loaded module?

在我的主页上,我有 4 个指向组件的链接,这些组件都属于名为 'CrudModule' 的功能模块。

我想知道如何延迟加载这个模块,这似乎不起作用:

我的应用-routing.module.ts:

const routes: Routes = [
   { path: 'add', loadChildren: () => import(`./crudFeatureModule/crud.module`).then(x => x.CrudModule) }
  , { path: 'search', loadChildren: () => import(`./crudFeatureModule/crud.module`).then(x => x.CrudModule) }
  , { path: 'importer', loadChildren: () => import(`./crudFeatureModule/crud.module`).then(x => x.CrudModule) }
  , { path: 'publier', loadChildren: () => import(`./crudFeatureModule/crud.module`).then(x => x.CrudModule) }
];

在官方 Angular 文档中,每个模块只提到一个组件,请参阅
这个例子来自 https://angular.io/guide/lazy-loading-ngmodules :

app-routing.module.ts:

const routes: Routes = [
  {
    path: 'customers',
    loadChildren: () => import('./customers/customers.module').then(mod => mod.CustomersModule)
  },

客户-routing.module.ts:

  import { CustomerListComponent } from './customer-list/customer-list.component';
  
  const routes: Routes = [
  {
    path: '',
    component: CustomerListComponent
  }
];

以上路径设置为空字符串。这是因为 AppRoutingModule 中的路径已经设置为 'customers'.

问题:延迟加载模块的路径总是需要为空,这是否意味着我应该将我的所有组件放在不同的模块中以实现延迟加载?换句话说,延迟加载的模块可以处理多个路由吗? 如果是这样,我应该怎么做?

如果你想加载单独页面中的每个组件,你必须为每个组件创建模块,这取决于你。

我像 blow 一样实现了我的应用程序的路由并且这个工作正常

  { path: 'person', loadChildren: './projects/person/person.module#PersonModule' },

通常,您的主路由器模块中的路由看起来像这样:

const routes: Routes = [
  {
    path: 'crud',
    loadChildren: () => import('./crudFeatureModule/crud.module').then(mod => mod.CrudModule)
  }
];

并调用 RouterModule.forRoot(routes).

然后,在您的 CrudModule 中,您将拥有:

const routes: Routes = [
  { path: 'add', component: AddComponent },
  { path: 'search', component: SearchComponent },
  { path: 'importer', component: ImporterComponent },
  { path: 'publier', component: PublierComponent }
];

并调用 RouterModule.forChild(routes).

您的网址将是 /crud/add/crud/search

当您使用 loadChildren 时,您延迟加载的模块需要知道如何加载子路由,即它需要将其路由注册到 RouterModule。明白我的意思了吗?

P.S。在构建路线时坚持使用一种语言通常被认为是最佳做法。 Je présume par le nom des routes que tu es francophone :-) généralement on évite de mélanger français et anglais si possible ^^