本節我們展示學生編輯組件的開發在步驟及每步的詳細代碼。
## 初始化
初始化包括組件初始化以及MockApi初始化:
### 組件初始化
來到student模塊,并使用angularCli進行完成的快速的初始化:
```bash
panjie@panjies-iMac student % pwd
/Users/panjie/github/mengyunzhi/angular11-guild/first-app/src/app/student
panjie@panjies-iMac student % ng g c edit
Your global Angular CLI version (11.2.13) is greater than your local version (11.0.7). The local Angular CLI version is used.
To disable this warning use "ng config -g cli.warnings.versionMismatch false".
CREATE src/app/student/edit/edit.component.css (0 bytes)
CREATE src/app/student/edit/edit.component.html (19 bytes)
CREATE src/app/student/edit/edit.component.spec.ts (612 bytes)
CREATE src/app/student/edit/edit.component.ts (267 bytes)
UPDATE src/app/student/student.module.ts (794 bytes)
```
### MockApi初始化
根據API信息,初始化MockApi信息:
```typescript
+++ b/first-app/src/app/mock-api/student.mock.api.ts
@@ -78,6 +78,49 @@ export class StudentMockApi implements MockApiInterface {
const ids = httpParams.getAll('ids');
Assert.isArray(ids, '未接收到ids');
})
+ }, {
+ method: 'GET',
+ url: '/student/(\\d+)',
+ result: (urlMatches: string[]) => {
+ const id = +urlMatches[1];
+ return {
+ id,
+ name: randomString('姓名'),
+ number: randomString('學號'),
+ phone: (139000000000 + randomNumber(99999999)).toString(),
+ email: randomString('前綴') + '@yunzhi.club',
+ clazz: {
+ id: randomNumber(),
+ name: randomString('班級名稱'),
+ teacher: {
+ id: randomNumber(),
+ name: randomString('教師名稱')
+ } as Teacher
+ } as Clazz
+ } as Student;
+ }
+ }, {
+ method: 'PUT',
+ url: '/student/(\\d+)',
+ result: (urlMatches: string[], options: RequestOptions) => {
+ const id = +urlMatches[1];
+ const student = options.body as Student;
+ return {
+ id,
+ name: student.name,
+ number: randomString('學號'),
+ phone: student.phone,
+ email: student.email,
+ clazz: {
+ id: student.clazz.id,
+ name: randomString('班級名稱'),
+ teacher: {
+ id: randomNumber(),
+ name: randomString('教師名稱')
+ } as Teacher
+ } as Clazz
+ } as Student;
+ }
}
];
}
```
### M層
根據Api信息建立補充M層方法 ---- `getById`:
```bash
+++ b/first-app/src/app/service/student.service.ts
@@ -37,6 +37,15 @@ export class StudentService {
return this.httpClient.delete<void>(url);
}
+
+ /**
+ * 獲取學生
+ * @param id 學生ID
+ */
+ getById(id: number): Observable<Student> {
+ return this.httpClient.get<Student>('/student/' + id.toString());
+ }
+
/**
```
`update`:
```typescript
+++ b/first-app/src/app/service/student.service.ts
/**
* 更新學生
* @param id 學生ID
* @param student 學生信息
*/
update(id: number, student: { name: string, phone: string, email: string, clazz: { id: number } }): Observable<Student> {
return this.httpClient.put<Student>(`/student/${id}`, student);
}
```
### 單元測試
對`getById()`方法的測試:
```typescript
+++ b/first-app/src/app/service/student.service.spec.ts
@@ -4,6 +4,7 @@ import {StudentService} from './student.service';
import {MockApiTestingModule} from '../mock-api/mock-api-testing.module';
import {HttpClient} from '@angular/common/http';
import {getTestScheduler} from 'jasmine-marbles';
+import {randomNumber} from '@yunzhi/ng-mock-api';
describe('StudentService', () => {
let service: StudentService;
@@ -93,5 +94,21 @@ describe('StudentService', () => {
console.log(jsonTest.name);
// jsonTest.sayHello();
});
+
+ fit('getById', () => {
+ // 返回前面已經請求的數據(如有),避免產生數據污染。
+ getTestScheduler().flush();
+
+ const id = randomNumber();
+ let called = false;
+ service.getById(id).subscribe(student => {
+ called = true;
+ expect(student).toBeTruthy();
+ });
+ expect(called).toBeFalse();
+
+ getTestScheduler().flush();
+ expect(called).toBeTrue();
+ });
});
```
測試通過:

對`update`方法的測試:
```typescript
+++ b/first-app/src/app/service/student.service.spec.ts
@@ -5,6 +5,7 @@ import {MockApiTestingModule} from '../mock-api/mock-api-testing.module';
import {HttpClient} from '@angular/common/http';
import {getTestScheduler} from 'jasmine-marbles';
import {randomNumber} from '@yunzhi/ng-mock-api';
+import {randomString} from '@yunzhi/ng-mock-api/testing';
describe('StudentService', () => {
let service: StudentService;
@@ -110,5 +111,25 @@ describe('StudentService', () => {
getTestScheduler().flush();
expect(called).toBeTrue();
});
+
+ fit('update', () => {
+ // 返回前面已經請求的數據(如有),避免產生數據污染。
+ getTestScheduler().flush();
+
+ const id = randomNumber();
+ let called = false;
+ service.update(id, {
+ name: randomString(),
+ email: randomString(),
+ phone: randomString(),
+ clazz: {id: randomNumber()}}).subscribe(student => {
+ called = true;
+ expect(student).toBeTruthy();
+ });
+ expect(called).toBeFalse();
+
+ getTestScheduler().flush();
+ expect(called).toBeTrue();
+ });
});
```

## 原型開發
更新學生與新增學生大同小異,不同的是更新學生時不能夠對學生的學號進行更新,原型代碼如下:
```html
<form class="container-sm" (ngSubmit)="onSubmit()" [formGroup]="formGroup">
<div class="mb-3 row">
<label class="col-sm-2 col-form-label">名稱</label>
<div class="col-sm-10">
<input type="text" class="form-control" formControlName="name">
<small class="text-danger" *ngIf="formGroup.get('name')!.invalid">
名稱不能為空
</small>
</div>
</div>
<div class="mb-3 row">
<label class="col-sm-2 col-form-label">學號</label>
<div class="col-sm-10">
<input type="text" readonly class="form-control-plaintext" formControlName="number">
</div>
</div>
<div class="mb-3 row">
<label class="col-sm-2 col-form-label">手機號</label>
<div class="col-sm-10">
<input type="text" class="form-control" formControlName="phone">
<small class="text-danger" *ngIf="formGroup.get('phone')!.invalid">
手機號格式不正確
</small>
</div>
</div>
<div class="mb-3 row">
<label class="col-sm-2 col-form-label">郵箱</label>
<div class="col-sm-10">
<input type="text" class="form-control" formControlName="email">
</div>
</div>
<div class="mb-3 row">
<label class="col-sm-2 col-form-label">班級</label>
<div class="col-sm-10">
<app-clazz-select formControlName="clazzId"></app-clazz-select>
<small class="text-danger" *ngIf="formGroup.get('clazzId')!.invalid">
必須選擇班級
</small>
</div>
</div>
<div class="mb-3 row">
<div class="col-sm-10 offset-2">
<button appLoading class="btn btn-primary" [disabled]="formGroup.invalid || formGroup.pending">
<i class="fa fa-save"></i>保存
</button>
</div>
</div>
</form>
```
根據原型中使用到的組件屬性及方法,初始化組件如下:
```typescript
+++ b/first-app/src/app/student/edit/edit.component.ts
@@ -1,4 +1,7 @@
-import { Component, OnInit } from '@angular/core';
+import {Component, OnInit} from '@angular/core';
+import {FormControl, FormGroup, Validators} from '@angular/forms';
+import {YzValidators} from '../../yz-validators';
+import {YzAsyncValidators} from '../../yz-async-validators';
@Component({
selector: 'app-edit',
@@ -6,10 +9,22 @@ import { Component, OnInit } from '@angular/core';
styleUrls: ['./edit.component.css']
})
export class EditComponent implements OnInit {
+ formGroup: FormGroup;
- constructor() { }
+ constructor(private yzAsyncValidators: YzAsyncValidators) {
+ this.formGroup = new FormGroup({
+ name: new FormControl('', Validators.required),
+ number: new FormControl('', Validators.required, yzAsyncValidators.numberNotExist()),
+ phone: new FormControl('', YzValidators.phone),
+ email: new FormControl(),
+ clazzId: new FormControl(null, Validators.required)
+ });
+ }
ngOnInit(): void {
}
+ onSubmit(): void {
+
+ }
}
```
### 單元測試
在組件中注入的`YzAsyncValidators`異步驗證器依賴于后臺API,在測試過程中,我們使用一個假的后臺來提供后臺API:
```typescript
+++ b/first-app/src/app/student/edit/edit.component.spec.ts
@@ -1,6 +1,8 @@
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {EditComponent} from './edit.component';
+import {MockApiTestingModule} from '../../mock-api/mock-api-testing.module';
+import {getTestScheduler} from 'jasmine-marbles';
describe('EditComponent', () => {
let component: EditComponent;
@@ -8,6 +10,7 @@ describe('EditComponent', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
+ imports: [MockApiTestingModule],
declarations: [EditComponent]
})
.compileComponents();
@@ -22,4 +25,15 @@ describe('EditComponent', () => {
fit('should create', () => {
expect(component).toBeTruthy();
});
+
+ /**
+ * 每個測試用例執行結束后,都執行一次此方法
+ */
+ afterEach(() => {
+ // 發送尚未發送的數據,可以避免兩次相近執行的單元測試不互相影響
+ getTestScheduler().flush();
+
+ // 統一調用自動檢測功能
+ fixture.autoDetectChanges();
+ });
});
```

至此,整體的初始化工作宣告結束,下一節開始完成功能實現。
| 鏈接 | 名稱 |
| ------------------------------------------------------------ | -------- |
| [https://github.com/mengyunzhi/angular11-guild/archive/step7.7.1.zip](https://github.com/mengyunzhi/angular11-guild/archive/step7.7.1.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 發布部署
- 第九章 總結