在计算机软件的世界里:**一切旨对象**。对于我们当前的程序而言,教师组件是个对象,班级组件是个对象,教师是个对象,班级同样也是个对象。在前面编码的过程中,我们直接声明了教师组件类及班级组件类,然后anguar根据这两个类为我们自己创建了对象。但并没有声明`教师`与`班级`类。本节中,我们使用声明类的方法来重写班级组件。 # 实体对象 在前台中在建立班级与教师对象时引用后台的术语`实体`,这是由于该`类`与`数据表`是一一对应的。前台建立实体与后台建立实体的思想一致,只是由于使用的语言不同,编写的技艺上有所差别而已。 我们在app文件夹下建立`norm/entity`文件夹,并在该文件夹下建立`Klass`及`Teacher`两个类: ``` panjiedeMac-Pro:app panjie$ tree . ├── app-routing.module.ts ├── app.component.html ├── app.component.sass ├── app.component.spec.ts ├── app.component.ts ├── app.module.ts ├── klass │   ├── index │   │   ├── index.component.html │   │   ├── index.component.sass │   │   ├── index.component.spec.ts │   │   └── index.component.ts │   └── klass.module.ts ├── norm │   └── entity │   ├── Klass.ts ① │   └── Teacher.ts ② └── teacher ├── teacher-add.component.html ├── teacher-add.component.ts ├── teacher-edit.component.html ├── teacher-edit.component.ts ├── teacher-index.component.html └── teacher-index.component.ts 5 directories, 19 files ``` ## Teacher norm/entity/teacher ``` /** * 教师 */ export class Teacher { ① id: number; name: string; username: string; email: string; sex: boolean; createTime: number; /** * 构造函数 * @param id id * @param username 用户名 * @param name 姓名 * @param email 邮箱 * @param sex 性别 */ constructor(id: number, username: string, name: string, email?➊: string, sex?: boolean) { this.id = id; this.name = name; this.username = username; this.email = email; this.sex = sex; } } ``` * ① 使用`export`关键字来抛出`Teacher`类。这样一来,其它的类便可以在文件中使用`import`关键字来引入该类。 * ➊ 表示可以传入该字段,也可以不传入。 ## Klass norm/entity/klass ``` import {Teacher} from './Teacher'; ① /** * 班级实体 */ export class Klass { id: number; name: string; teacher: Teacher; /** * 构造函数 * @param id id * @param name 名称 * @param teacher 教师 */ constructor(id: number, name: string, teacher: Teacher) { this.id = id; this.name = name; this.teacher = teacher; } } ``` * ① 由当前文件夹下的`Teacher.ts`中引入其文件中使用`export`关键字抛出的`Teacher`类。 # 重构组件 有了更加面向对象的实体类后,我们在班级的`index`组件中这样使用: ``` import {Klass} from '../../norm/entity/Klass'; import {Teacher} from '../../norm/entity/Teacher'; ... /* 班级 */ klasses = [ new Klass(1, '计科1901班', new Teacher(1, 'zhagnsan', '张三')), new Klass(2, '软件1902班', new Teacher(2, 'lisi', '李四')) ]; ``` 有人说老师写来写去的,我们增加了这么多的代码,但一点也没有觉出来简单呀。当前有这种想法是正常的,当然也说明了我们还没有领会软件开发解决的本质问题是:**如何更快、更好地满足不断变化的需求**。有人说杀死一个程序员最快最简单的方法是“做他的项目经理,然后每天变更一次需求”也充分的印证了这一点。 在此举一个不实际的小例子:有一天后台的人员按需求(抽疯)将`Klass`实体中的`name`变更为`mingcheng`。在我们当前的设计中借助于`webstorm`我们找到`Klass`类中的`name`字段,使用`shift + f6`快捷键进行重命名后,所有使用了该字段的地方都自动地进行重命名: ![](https://img.kancloud.cn/f1/65/f1659ef843b0aab82055f9dcf81dab3b_640x212.gif) 不止如此,我们在进行V层的开发过程中,编辑器还可以非常智能的自动填充提示,以后这种拼写的错误你想出都难了。 ![](https://img.kancloud.cn/72/f5/72f552a9a64f2941ac1fe90e777d081f_804x168.png) # 参考文档 | 名称 | 链接 | 预计学习时长(分) | | --- | --- | --- | | 源码地址 | [https://github.com/mengyunzhi/spring-boot-and-angular-guild/releases/tag/step3.2.4](https://github.com/mengyunzhi/spring-boot-and-angular-guild/releases/tag/step3.2.4) | - |