# TypeScript類
本節我們共同完成上節中的作業:新建Teacher類。
## 實體類
在團隊項中,我們更愿意將與后臺返回數據對應的類稱為實體Entity類,表示此類與后臺返回的數據格式一致。教師數據便是典型的由后臺獲取的數據,所以我們在`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
```
然后進入該文件夾,使用angular cli自動創建一個普通的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將自動創建一個Teacher類及該類對應的測試文件。
## class Teacher
此時我們便可以定義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;
}
```
接著定義構造函數:
```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;
+ }
}
```
接下來,我們便可以在Login的相關功能上使用該類型了。
### 測試
```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();
});
});
```
## 規定類型
使用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(), '子組件進行了數據彈射', teacher);
this.login = true;
}
```
重寫測試
```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 用戶登錄', () => {
// 啟動自動變更檢測
fixture.autoDetectChanges();
- component.teacher = {username: '張三', password: 'codedemo.club'};
+ component.teacher = {username: '張三', password: 'codedemo.club'} as Teacher;
component.onSubmit();
});
});
```
## 驗證
是時候展示偉大的TypeScript以及`ng t`的偉大魅力了!在日常的開發工作中,我們常常因為不敢重構而放棄重構的想法,特別是一些弱類型的語言,肯定動一動某個屬性的名稱都會給我們帶來惡夢。而有了TypeScript加之Angular為我們準備的`ng t`,我們再也不懼怕重構了。
此時我們可以使用`ng t`來驗證本次重構是否成功。在使用`ng t`前,我們需要將所有的`fdescribe`、`fit`進行復原,以使得所有的測試文件均得到執行。又由于我們為每個組件都定義了對應的測試文件,所以若測試的代碼全部成功的執行,則說明此次重構沒有任何問題。

## 本節作業
我們在Teacher對應的測試文件中如下實例化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();
});
});
```
而如果我們少填寫一個參數,或是將對應參數的值輸入undefined則會拋出異常:


請**嘗試**通過自己的能力使Teacher的構造函數支持默認值,使以下代碼正常執行:
```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) | |
| 本節源碼 | [https://github.com/mengyunzhi/angular11-guild/archive/step3.6.zip](https://github.com/mengyunzhi/angular11-guild/archive/step3.6.zip) | |
- 序言
- 第一章 Hello World
- 1.1 環境安裝
- 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 請求后臺數據
- 2.2.1 HttpClient
- 2.2.2 請求數據
- 2.2.3 模塊與依賴注入
- 2.2.4 異步與回調函數
- 2.2.5 集成測試
- 2.2.6 本章小節
- 2.3 新增教師
- 2.3.1 組件初始化
- 2.3.2 [(ngModel)]
- 2.3.3 對接后臺
- 2.3.4 路由
- 2.4 編輯教師
- 2.4.1 組件初始化
- 2.4.2 獲取路由參數
- 2.4.3 插值與模板表達式
- 2.4.4 初識泛型
- 2.4.5 更新教師
- 2.4.6 測試中的路由
- 2.5 刪除教師
- 2.6 收尾工作
- 2.6.1 RouterLink
- 2.6.2 fontawesome圖標庫
- 2.6.3 firefox
- 2.7 總結
- 第三章 用戶登錄
- 3.1 初識單元測試
- 3.2 http概述
- 3.3 Basic access authentication
- 3.4 著陸組件
- 3.5 @Output
- 3.6 TypeScript 類
- 3.7 瀏覽器緩存
- 3.8 總結
- 第四章 個人中心
- 4.1 原型
- 4.2 管道
- 4.3 對接后臺
- 4.4 x-auth-token認證
- 4.5 攔截器
- 4.6 小結
- 第五章 系統菜單
- 5.1 延遲及測試
- 5.2 手動創建組件
- 5.3 隱藏測試信息
- 5.4 規劃路由
- 5.5 定義菜單
- 5.6 注銷
- 5.7 小結
- 第六章 班級管理
- 6.1 新增班級
- 6.1.1 組件初始化
- 6.1.2 MockApi 新建班級
- 6.1.3 ApiInterceptor
- 6.1.4 數據驗證
- 6.1.5 教師選擇列表
- 6.1.6 MockApi 教師列表
- 6.1.7 代碼重構
- 6.1.8 小結
- 6.2 教師列表組件
- 6.2.1 初始化
- 6.2.2 響應式表單
- 6.2.3 getTestScheduler()
- 6.2.4 應用組件
- 6.2.5 小結
- 6.3 班級列表
- 6.3.1 原型設計
- 6.3.2 初始化分頁
- 6.3.3 MockApi
- 6.3.4 靜態分頁
- 6.3.5 動態分頁
- 6.3.6 @Input()
- 6.4 編輯班級
- 6.4.1 測試模塊
- 6.4.2 響應式表單驗證
- 6.4.3 @Input()
- 6.4.4 FormGroup
- 6.4.5 自定義FormControl
- 6.4.6 代碼重構
- 6.4.7 小結
- 6.5 刪除班級
- 6.6 集成測試
- 6.6.1 惰性加載
- 6.6.2 API攔截器
- 6.6.3 路由與跳轉
- 6.6.4 ngStyle
- 6.7 初識Service
- 6.7.1 catchError
- 6.7.2 單例服務
- 6.7.3 單元測試
- 6.8 小結
- 第七章 學生管理
- 7.1 班級列表組件
- 7.2 新增學生
- 7.2.1 exports
- 7.2.2 自定義驗證器
- 7.2.3 異步驗證器
- 7.2.4 再識DI
- 7.2.5 屬性型指令
- 7.2.6 完成功能
- 7.2.7 小結
- 7.3 單元測試進階
- 7.4 學生列表
- 7.4.1 JSON對象與對象
- 7.4.2 單元測試
- 7.4.3 分頁模塊
- 7.4.4 子組件測試
- 7.4.5 重構分頁
- 7.5 刪除學生
- 7.5.1 第三方dialog
- 7.5.2 批量刪除
- 7.5.3 面向對象
- 7.6 集成測試
- 7.7 編輯學生
- 7.7.1 初始化
- 7.7.2 自定義provider
- 7.7.3 更新學生
- 7.7.4 集成測試
- 7.7.5 可訂閱的路由參數
- 7.7.6 小結
- 7.8 總結
- 第八章 其它
- 8.1 打包構建
- 8.2 發布部署
- 第九章 總結