# TypeScript類
本節(jié)我們共同完成上節(jié)中的作業(yè):新建Teacher類。
## 實(shí)體類
在團(tuán)隊(duì)項(xiàng)中,我們更愿意將與后臺(tái)返回?cái)?shù)據(jù)對(duì)應(yīng)的類稱為實(shí)體Entity類,表示此類與后臺(tái)返回的數(shù)據(jù)格式一致。教師數(shù)據(jù)便是典型的由后臺(tái)獲取的數(shù)據(jù),所以我們?cè)赻app`文件夾下新下`entity`文件夾:
```bash
panjie@panjies-Mac-Pro app % pwd
/Users/panjie/github/mengyunzhi/angular11-guild/first-app/src/app
panjie@panjies-Mac-Pro app % tree -L 1
.
├── add
├── app-routing.module.ts
├── app.component.css
├── app.component.html
├── app.component.spec.ts
├── app.component.ts
├── app.module.ts
├── edit
├── entity ??
├── index
└── login
5 directories, 6 files
```
然后進(jìn)入該文件夾,使用angular cli自動(dòng)創(chuàng)建一個(gè)普通的teacher類:
```bash
panjie@panjies-Mac-Pro entity % pwd
/Users/panjie/github/mengyunzhi/angular11-guild/first-app/src/app/entity
panjie@panjies-Mac-Pro entity % ng g class teacher
CREATE src/app/entity/teacher.spec.ts (158 bytes)
CREATE src/app/entity/teacher.ts (25 bytes)
```
Angualr cli將自動(dòng)創(chuàng)建一個(gè)Teacher類及該類對(duì)應(yīng)的測(cè)試文件。
## class Teacher
此時(shí)我們便可以定義Teacher的屬性了:
```typescript
+++ b/first-app/src/app/entity/teacher.ts
@@ -1,2 +1,11 @@
+/**
+ * 教師(用戶)
+ */
export class Teacher {
+ id: number;
+ email: string;
+ name: string;
+ password: string;
+ sex: boolean;
+ username: string;
}
```
接著定義構(gòu)造函數(shù):
```typescript
+++ b/first-app/src/app/entity/teacher.ts
@@ -7,5 +7,14 @@ export class Teacher {
name: string;
password: string;
sex: boolean;
username: string;
+
+ constructor(id: number, email: string, name: string, password: string, sex: boolean, username: string) {
+ this.id = id;
+ this.email = email;
+ this.name = name;
+ this.password = password;
+ this.sex = sex;
+ this.username = username;
+ }
}
```
接下來(lái),我們便可以在Login的相關(guān)功能上使用該類型了。
### 測(cè)試
```typescript
+++ b/first-app/src/app/entity/teacher.spec.ts
@@ -2,6 +2,6 @@ import { Teacher } from './teacher';
describe('Teacher', () => {
it('should create an instance', () => {
- expect(new Teacher()).toBeTruthy();
+ expect(new Teacher(1, 'email', 'name', 'password', true, 'username')).toBeTruthy();
});
});
```
## 規(guī)定類型
使用Teacher類重寫登錄組件:
```typescript
+++ b/first-app/src/app/login/login.component.ts
@@ -1,5 +1,6 @@
import {Component, EventEmitter, OnInit, Output} from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http';
+import {Teacher} from '../entity/teacher';
@Component({
selector: 'app-login',
@@ -7,13 +8,10 @@ import {HttpClient, HttpHeaders} from '@angular/common/http';
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
- teacher = {} as {
- username: string,
- password: string
- };
+ teacher = {} as Teacher;
@Output()
- beLogin = new EventEmitter<{ username: string, name: string, email: string, sex: boolean }>();
+ beLogin = new EventEmitter<Teacher>();
constructor(private httpClient: HttpClient) {
}
@@ -31,7 +29,7 @@ export class LoginComponent implements OnInit {
httpHeaders = httpHeaders.append('Authorization', 'Basic ' + authToken);
this.httpClient
- .get<any>(
+ .get<Teacher>(
'http://angular.api.codedemo.club:81/teacher/login',
{headers: httpHeaders})
.subscribe(teacher => this.beLogin.emit(teacher),
```
重寫Index 組件:
```typescript
+++ b/first-app/src/app/index/index.component.ts
@@ -1,4 +1,5 @@
import {Component, OnInit} from '@angular/core';
+import {Teacher} from '../entity/teacher';
@Component({
selector: 'app-index',
@@ -15,7 +16,7 @@ export class IndexComponent implements OnInit {
ngOnInit(): void {
}
- onLogin(teacher: { username: string, name: string, email: string, sex: boolean }): void {
+ onLogin(teacher: Teacher): void {
console.log(new Date().toTimeString(), '子組件進(jìn)行了數(shù)據(jù)彈射', teacher);
this.login = true;
}
```
重寫測(cè)試
```typescript
+++ b/first-app/src/app/login/login.component.spec.ts
@@ -3,6 +3,7 @@ import {ComponentFixture, TestBed} from '@angular/core/testing';
import {LoginComponent} from './login.component';
import {FormsModule} from '@angular/forms';
import {HttpClientModule} from '@angular/common/http';
+import {Teacher} from '../entity/teacher';
describe('LoginComponent', () => {
let component: LoginComponent;
@@ -45,7 +46,7 @@ describe('LoginComponent', () => {
it('onSubmit 用戶登錄', () => {
// 啟動(dòng)自動(dòng)變更檢測(cè)
fixture.autoDetectChanges();
- component.teacher = {username: '張三', password: 'codedemo.club'};
+ component.teacher = {username: '張三', password: 'codedemo.club'} as Teacher;
component.onSubmit();
});
});
```
## 驗(yàn)證
是時(shí)候展示偉大的TypeScript以及`ng t`的偉大魅力了!在日常的開發(fā)工作中,我們常常因?yàn)椴桓抑貥?gòu)而放棄重構(gòu)的想法,特別是一些弱類型的語(yǔ)言,肯定動(dòng)一動(dòng)某個(gè)屬性的名稱都會(huì)給我們帶來(lái)惡夢(mèng)。而有了TypeScript加之Angular為我們準(zhǔn)備的`ng t`,我們?cè)僖膊粦峙轮貥?gòu)了。
此時(shí)我們可以使用`ng t`來(lái)驗(yàn)證本次重構(gòu)是否成功。在使用`ng t`前,我們需要將所有的`fdescribe`、`fit`進(jìn)行復(fù)原,以使得所有的測(cè)試文件均得到執(zhí)行。又由于我們?yōu)槊總€(gè)組件都定義了對(duì)應(yīng)的測(cè)試文件,所以若測(cè)試的代碼全部成功的執(zhí)行,則說(shuō)明此次重構(gòu)沒有任何問(wèn)題。

## 本節(jié)作業(yè)
我們?cè)赥eacher對(duì)應(yīng)的測(cè)試文件中如下實(shí)例化Teacher:
```typescript
+++ b/first-app/src/app/entity/teacher.spec.ts
describe('Teacher', () => {
it('should create an instance', () => {
expect(new Teacher(1, 'email', 'name', 'password', true, 'username')).toBeTruthy();
});
});
```
而如果我們少填寫一個(gè)參數(shù),或是將對(duì)應(yīng)參數(shù)的值輸入undefined則會(huì)拋出異常:


請(qǐng)**嘗試**通過(guò)自己的能力使Teacher的構(gòu)造函數(shù)支持默認(rèn)值,使以下代碼正常執(zhí)行:
```typescript
describe('Teacher', () => {
it('should create an instance', () => {
expect(new Teacher()).toBeTruthy();
const id = 123;
expect(new Teacher(id).toBeTruthy();
const email = 'zhangsan@codedemo.club';
expect(new Teacher(id, email).toBeTruthy();
});
});
```
| 名稱 | 地址 | 備注 |
| --------------- | ------------------------------------------------------------ | ---- |
| TypeScript 類 | [https://www.tslang.cn/docs/handbook/classes.html](https://www.tslang.cn/docs/handbook/classes.html) | |
| TypeScript 類型 | [https://www.tslang.cn/docs/handbook/advanced-types.html](https://www.tslang.cn/docs/handbook/advanced-types.html) | |
| 本節(jié)源碼 | [https://github.com/mengyunzhi/angular11-guild/archive/step3.6.zip](https://github.com/mengyunzhi/angular11-guild/archive/step3.6.zip) | |
- 序言
- 第一章 Hello World
- 1.1 環(huán)境安裝
- 1.2 Hello Angular
- 1.3 Hello World!
- 第二章 教師管理
- 2.1 教師列表
- 2.1.1 初始化原型
- 2.1.2 組件生命周期之初始化
- 2.1.3 ngFor
- 2.1.4 ngIf、ngTemplate
- 2.1.5 引用 Bootstrap
- 2.2 請(qǐng)求后臺(tái)數(shù)據(jù)
- 2.2.1 HttpClient
- 2.2.2 請(qǐng)求數(shù)據(jù)
- 2.2.3 模塊與依賴注入
- 2.2.4 異步與回調(diào)函數(shù)
- 2.2.5 集成測(cè)試
- 2.2.6 本章小節(jié)
- 2.3 新增教師
- 2.3.1 組件初始化
- 2.3.2 [(ngModel)]
- 2.3.3 對(duì)接后臺(tái)
- 2.3.4 路由
- 2.4 編輯教師
- 2.4.1 組件初始化
- 2.4.2 獲取路由參數(shù)
- 2.4.3 插值與模板表達(dá)式
- 2.4.4 初識(shí)泛型
- 2.4.5 更新教師
- 2.4.6 測(cè)試中的路由
- 2.5 刪除教師
- 2.6 收尾工作
- 2.6.1 RouterLink
- 2.6.2 fontawesome圖標(biāo)庫(kù)
- 2.6.3 firefox
- 2.7 總結(jié)
- 第三章 用戶登錄
- 3.1 初識(shí)單元測(cè)試
- 3.2 http概述
- 3.3 Basic access authentication
- 3.4 著陸組件
- 3.5 @Output
- 3.6 TypeScript 類
- 3.7 瀏覽器緩存
- 3.8 總結(jié)
- 第四章 個(gè)人中心
- 4.1 原型
- 4.2 管道
- 4.3 對(duì)接后臺(tái)
- 4.4 x-auth-token認(rèn)證
- 4.5 攔截器
- 4.6 小結(jié)
- 第五章 系統(tǒng)菜單
- 5.1 延遲及測(cè)試
- 5.2 手動(dòng)創(chuàng)建組件
- 5.3 隱藏測(cè)試信息
- 5.4 規(guī)劃路由
- 5.5 定義菜單
- 5.6 注銷
- 5.7 小結(jié)
- 第六章 班級(jí)管理
- 6.1 新增班級(jí)
- 6.1.1 組件初始化
- 6.1.2 MockApi 新建班級(jí)
- 6.1.3 ApiInterceptor
- 6.1.4 數(shù)據(jù)驗(yàn)證
- 6.1.5 教師選擇列表
- 6.1.6 MockApi 教師列表
- 6.1.7 代碼重構(gòu)
- 6.1.8 小結(jié)
- 6.2 教師列表組件
- 6.2.1 初始化
- 6.2.2 響應(yīng)式表單
- 6.2.3 getTestScheduler()
- 6.2.4 應(yīng)用組件
- 6.2.5 小結(jié)
- 6.3 班級(jí)列表
- 6.3.1 原型設(shè)計(jì)
- 6.3.2 初始化分頁(yè)
- 6.3.3 MockApi
- 6.3.4 靜態(tài)分頁(yè)
- 6.3.5 動(dòng)態(tài)分頁(yè)
- 6.3.6 @Input()
- 6.4 編輯班級(jí)
- 6.4.1 測(cè)試模塊
- 6.4.2 響應(yīng)式表單驗(yàn)證
- 6.4.3 @Input()
- 6.4.4 FormGroup
- 6.4.5 自定義FormControl
- 6.4.6 代碼重構(gòu)
- 6.4.7 小結(jié)
- 6.5 刪除班級(jí)
- 6.6 集成測(cè)試
- 6.6.1 惰性加載
- 6.6.2 API攔截器
- 6.6.3 路由與跳轉(zhuǎn)
- 6.6.4 ngStyle
- 6.7 初識(shí)Service
- 6.7.1 catchError
- 6.7.2 單例服務(wù)
- 6.7.3 單元測(cè)試
- 6.8 小結(jié)
- 第七章 學(xué)生管理
- 7.1 班級(jí)列表組件
- 7.2 新增學(xué)生
- 7.2.1 exports
- 7.2.2 自定義驗(yàn)證器
- 7.2.3 異步驗(yàn)證器
- 7.2.4 再識(shí)DI
- 7.2.5 屬性型指令
- 7.2.6 完成功能
- 7.2.7 小結(jié)
- 7.3 單元測(cè)試進(jìn)階
- 7.4 學(xué)生列表
- 7.4.1 JSON對(duì)象與對(duì)象
- 7.4.2 單元測(cè)試
- 7.4.3 分頁(yè)模塊
- 7.4.4 子組件測(cè)試
- 7.4.5 重構(gòu)分頁(yè)
- 7.5 刪除學(xué)生
- 7.5.1 第三方dialog
- 7.5.2 批量刪除
- 7.5.3 面向?qū)ο?/a>
- 7.6 集成測(cè)試
- 7.7 編輯學(xué)生
- 7.7.1 初始化
- 7.7.2 自定義provider
- 7.7.3 更新學(xué)生
- 7.7.4 集成測(cè)試
- 7.7.5 可訂閱的路由參數(shù)
- 7.7.6 小結(jié)
- 7.8 總結(jié)
- 第八章 其它
- 8.1 打包構(gòu)建
- 8.2 發(fā)布部署
- 第九章 總結(jié)