首页 > 解决方案 > 我如何将延迟加载模块中的组件用作其他未延迟加载的组件中的子组件?

问题描述

我有一个延迟加载的模块。该模块的一部分是 CreateEmployeeComponent。我还有不是延迟加载的主组件,它的路由路径在 app-routing.module.ts 文件中定义。当我尝试将 CreateEmployeeComponent 用作子组件时在 Home 组件中我得到错误 app-create-employee is not a known element 这是预期的,因为 app.module.ts 不知道 CreateEmployeeComponent 在我的 EmployeeModule 的声明数组中声明。如果我不使用延迟加载,我会在 app.module.ts 文件中插入 EmployeeModule,错误将得到修复。我现在无法在我的 app.module.ts 中插入 EmployeeModule,因为这样他就不会被延迟加载。

我怎么解决这个问题?

//app.module.ts

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    PageNotFoundComponent,

  ],
  imports: [
    BrowserModule,
    SharedModule,
    AppRoutingModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }


// app-routing.module.ts

const routes: Routes = [
  { path: 'home', component: HomeComponent },
  { path: '', redirectTo: '/home', pathMatch: 'full' },
  {path:'employees' , data: {preload:true}, loadChildren:'./modules/employee/employee.module#EmployeeModule'},
  { path: '**', component: PageNotFoundComponent },
];


//employee-routing.module.ts

const routes: Routes = [

    { path: '', component: ListEmployeesComponent },
    { path: 'create', component: CreateEmployeeComponent },
    { path: 'edit/:id', component: CreateEmployeeComponent },
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class EmployeeRoutingModule { }


//employee.module.ts

@NgModule({
  imports: [
    EmployeeRoutingModule,
    SharedModule
  ],
  declarations: [
    CreateEmployeeComponent,
    ListEmployeesComponent,
    CompoWithChildrensComponent,
    ChildrenOneComponent,
    ChildrenTwoComponent
  ],
  exports:[
    CreateEmployeeComponent
  ]
})
export class EmployeeModule { }




标签: angular

解决方案


因为AppModule使用来自的组件EmployeeModule,所以您必须导入EmployeeModule.

您可以分成EmployeeModule两个模块;一个模块,CreateEmployeeComponent一个模块,其余模块。您可以导入第一个模块并延迟加载第二个模块。

您必须自己确定这对您的应用程序是否实用且有用。


推荐阅读