1.2.模块划分

推荐模块划分图

后期补充

核心模块

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

创建模块

ng g m core

如何保障core只被加载一次?

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

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

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

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


export class CoreModule {

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

}

共享模块

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

创建模块

ng g m shared

常见的共享模块有:

官方文档中的常用模块

  • CommonModule:导出所有基本的 Angular 指令和管道,例如 NgIfNgForOfDecimalPipe 等。

  • ReactiveFormsModule:导出响应式表单所需的基础设施和指令。

  • FormsModule:导出模板驱动表单所需的提供商和指令。

  • NgZorroAntdModule

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

参考代码

NGMODULE

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

src/app/shared/shared.module.ts

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

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

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

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

Last updated

Was this helpful?