- 创建模块:
- 使用Angular CLI命令
ng generate module <module - name>
来创建新模块。例如,若要创建名为 feature
的模块,命令为 ng generate module feature
。此命令会在项目中生成一个新的模块文件结构。
- 模块文件作用:
<module - name>.module.ts
:这是模块的主文件。它使用 @NgModule
装饰器来定义模块。@NgModule
接受一个配置对象,其中常见的属性有:
imports
:用于导入该模块所需的其他模块,比如 CommonModule
(提供常用的指令和管道,如 ngIf
、ngFor
等),若模块中要使用路由,还需导入 RouterModule
等。
declarations
:声明该模块内拥有的组件、指令和管道。只有在此处声明的,才能在该模块内的模板中使用。
exports
:如果想让该模块内声明的某些组件、指令或管道能在其他模块中使用,就将它们添加到 exports
数组中。通常,会把一些公用的组件等导出。
providers
:用于注册该模块需要的服务。服务在这里注册后,整个应用中都可以使用(如果是根模块注册的话)。若模块是懒加载模块,在该模块中注册的服务只会在该模块加载时创建实例。
- 配置路由(如果模块涉及路由):
- 创建路由文件,通常命名为
<module - name>-routing.module.ts
。例如,对于 feature
模块,为 feature - routing.module.ts
。
- 在路由文件中,使用
RouterModule.forChild
方法来配置模块的路由。forChild
方法接受一个路由数组,每个路由对象包含 path
(路径)和 component
(对应的组件)等属性。例如:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { FeatureComponent } from './feature.component';
const routes: Routes = [
{ path: 'feature - path', component: FeatureComponent }
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class FeatureRoutingModule {}
- 然后在模块主文件
<module - name>.module.ts
的 imports
数组中导入该路由模块,如 import { FeatureRoutingModule } from './feature - routing.module';
。
- 在主模块或相关模块中导入新模块:
- 如果新模块是应用的核心功能模块,通常在
app.module.ts
的 imports
数组中导入。例如,若新模块名为 feature
,则添加 import { FeatureModule } from './feature.module';
到 app.module.ts
的导入部分,然后在 imports
数组中添加 FeatureModule
。
- 如果新模块是某个特定功能区域的模块,在相关的父模块中导入,比如某个业务模块的子模块,就在该业务模块的
imports
数组中导入。