> For the complete documentation index, see [llms.txt](https://moluo.gitbook.io/notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://moluo.gitbook.io/notes/bian-cheng-xue-xi/qian-duan/angular-da-zao-qi-ye-ji-xie-zuo-ping-tai/1.2.-mo-kuai-hua-fen.md).

# 1.2.模块划分

## 推荐模块划分图

```bash
后期补充
```

## 核心模块

用于放置哪些只加载一次的组件和服务（比如header、footer、sidebar）

### 创建模块

```bash
ng g m core
```

### 如何保障core只被加载一次？

为了保障core模块只被加载一次，新建以下两个文件

src/app/core/module-import-guard.ts

```typescript
export function throwIfAlreadyLoaded(parentModule: any, moduleName: string) {
  if (parentModule) {
    throw new Error(`${moduleName} has already been loaded. Import Core modules in the AppModule only.`);
  }
}
```

src/app/core/core.module.ts

```typescript
import {NgModule, Optional, SkipSelf} from '@angular/core';
import {throwIfAlreadyLoaded} from './module-import-guard';


export class CoreModule {

  constructor(@Optional() @SkipSelf() parentModule: CoreModule) {
    throwIfAlreadyLoaded(parentModule, 'CoreModule');
  }

}
```

## 共享模块

用于导入导出模块，放置那些公共的模块

### 创建模块

```bash
ng g m shared
```

### 常见的共享模块有：

官方文档中的[常用模块](https://angular.cn/guide/frequent-ngmodules)

* CommonModule：导出所有基本的 Angular 指令和管道，例如 `NgIf`、`NgForOf`、`DecimalPipe` 等。
* ReactiveFormsModule：导出响应式表单所需的基础设施和指令。
* FormsModule：导出模板驱动表单所需的提供商和指令。
* NgZorroAntdModule

更多的模块说明可直接阅读源码或通过以下url查询：<https://angular.cn/api>

### 参考代码

NGMODULE

导出响应式表单所需的基础设施和指令，使其能用于任何导入了本模块的 NgModule 中。

src/app/shared/shared.module.ts

```typescript
import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
import {NgZorroAntdModule} from 'ng-zorro-antd';

@NgModule({
  declarations: [],
  imports: [
    CommonModule,
    ReactiveFormsModule,
    FormsModule,
    NgZorroAntdModule
  ],
  exports: [
    CommonModule,
    ReactiveFormsModule,
    FormsModule,
    NgZorroAntdModule
  ]
})
export class SharedModule {
}
```

## 工具文件夹

用于存放工具类

src/app/utils

工具类的命令格式为：{类名}.util.ts

示例：src/app/utils/svg.util.ts

```typescript
import {DomSanitizer} from '@angular/platform-browser';
import {MdIconRegistry} from '@angular/material';

export const loadSvgResource = (ir: MdIconRegistry, ds: DomSanitizer) => {
  const imgDir = 'assets/img';
  const sidebarDir = '${imgDir}/sidebar';
  ir.addSvgIcon('gifts', ds.bypassSecurityTrustResourceUrl('${sidebar}/gifts.svg'));
};
```

## 领域对象文件夹

用于存放domain

src/app/domain

领域对象的命令格式为：{类名}.model.ts

示例：src/app/domain/user.model.ts

```typescript
export interface User {
  id?: string;
  email: string;
  name?: string;
  password?: string;
  avatar?: string;
  address?: Address;
  dateOfBirth?: string;
}
```

> id?: string说明：当新增用户的时候，是没有id的，使用?号表示id字段是可有可无的。
