合理的分頁數據也夠幫助我們快速的發現在組件中發生的邏輯性錯誤,本節我展示如何在MockApi中返回一個合格的分頁數據。
## 初始化
和后臺的提供的教師分頁接口相同,后臺還提供了一個班級分頁接口:
```bash
GET /clazz/page
```
| **類型Type** | **名稱Name** | **描述Description** | 必填 | **類型Schema** | 默認值 |
| :------------ | :----------- | :----------------------- | ---- | :--------------------------- | --------- |
| Param請求參數 | `page` | 第幾頁 | 否 | `number` | 0 |
| Param請求參數 | `size` | 每頁大小 | 否 | `number` | 20 |
| Param請求參數 | sort | 排序字段及方式(支持多個) | 否 | `string`例:`sort=name,desc` | `id,desc` |
| Response響應 | | Status Code: 200 | | `Page<Clazz>` | |
據此建立相應在clazz對應的MockApi文件夾,我們新建如下模擬返回數據:
```typescript
+++ b/first-app/src/app/mock-api/clazz.mock.api.ts
@@ -1,4 +1,7 @@
import {ApiInjector, MockApiInterface, randomNumber, RequestOptions} from '@yunzhi/ng-mock-api';
+import {Clazz} from '../entity/clazz';
+import {Teacher} from '../entity/teacher';
+import {Page} from '../entity/page';
/**
* 班級模擬API
@@ -30,6 +33,30 @@ export class ClazzMockApi implements MockApiInterface {
}
};
}
+ },
+ {
+ method: 'GET',
+ url: '/clazz/page',
+ result: () => {
+ const size = 20;
+ const clazzes = new Array<Clazz>();
+ for (let i = 0; i < size; i++) {
+ clazzes.push(new Clazz({
+ id: i,
+ name: '班級',
+ teacher: new Teacher({
+ id: i,
+ name: '教師'
+ })
+ }));
+ }
+ return new Page<Clazz>({
+ content: clazzes,
+ number: 2,
+ size,
+ numberOfElements: 20
+ });
+ }
}
];
}
```
如上述代碼所示,模擬返回數據中的大多數代碼與我們在上節組件中寫的模擬代碼相同。
## 測試
MockApi完后后,我們在動態測試模塊中加入相應的攔截器:
```typescript
+++ b/first-app/src/app/clazz/clazz.component.spec.ts
@@ -1,6 +1,9 @@
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {ClazzComponent} from './clazz.component';
+import {MockApiTestingInterceptor} from '@yunzhi/ng-mock-api/testing';
+import {ClazzMockApi} from '../mock-api/clazz.mock.api';
+import {getTestScheduler} from 'jasmine-marbles';
describe('ClazzComponent', () => {
let component: ClazzComponent;
@@ -8,7 +11,10 @@ describe('ClazzComponent', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
- declarations: [ClazzComponent]
+ declarations: [ClazzComponent],
+ imports: [
+ MockApiTestingInterceptor.forRoot([ClazzMockApi])
+ ]
})
.compileComponents();
});
```
然后手動控制數據返回,手動渲染組件:
```typescript
fit('should create', () => {
expect(component).toBeTruthy();
- fixture.autoDetectChanges();
+ getTestScheduler().flush();
+ fixture.detectChanges();
});
});
```
最后,刪除C層中生成模擬數據的方法,轉而調用`httpClient`從而完成班級分頁的請求:
```typescript
+++ b/first-app/src/app/clazz/clazz.component.ts
@@ -2,6 +2,7 @@ import {Component, OnInit} from '@angular/core';
import {Page} from '../entity/page';
import {Clazz} from '../entity/clazz';
import {Teacher} from '../entity/teacher';
+import {HttpClient} from '@angular/common/http';
@Component({
selector: 'app-clazz',
@@ -23,26 +24,11 @@ export class ClazzComponent implements OnInit {
numberOfElements: 0
});
- constructor() {
+ constructor(private httpClient: HttpClient) {
}
ngOnInit(): void {
- const clazzes = new Array<Clazz>();
- for (let i = 0; i < this.size; i++) {
- clazzes.push(new Clazz({
- id: i,
- name: '班級',
- teacher: new Teacher({
- id: i,
- name: '教師'
- })
- }));
- }
- this.pageData = new Page<Clazz>({
- content: clazzes,
- number: 2,
- size: this.size,
- numberOfElements: 20
- });
+ this.httpClient.get<Page<Clazz>>('/clazz/page') ??
+ .subscribe(pageData => this.pageData = pageData);
}
}
```
在這里使用了泛型來先后指定了當前`get`的元素類型為`Page`以及當前`Page`中的元素類型為`Clazz`,還需要注意的一點是雖然我們可以使用`/clazz/page`、`clazz/page`兩種方式,但無論使用哪一種,都要保持組件中的調用與MockApi中的url相統一。
在組件的動態測試模塊中加入MockApi攔截器并進行測試如下:
```typescript
+++ b/first-app/src/app/clazz/clazz.component.spec.ts
imports: [
HttpClientModule
],
providers: [
{
provide: HTTP_INTERCEPTORS, multi: true,
useClass: MockApiTestingInterceptor.forRoot([ClazzMockApi])
}
]
@@ -27,6 +27,7 @@ describe('ClazzComponent', () => {
fit('should create', () => {
expect(component).toBeTruthy();
- fixture.autoDetectChanges();
+ getTestScheduler().flush();
+ fixture.detectChanges();
});
});
```
最終效果如下:

## 完善API
### 隨機數
在返回的班級名稱、教師名稱上加入一些隨機數,會起到更好的模擬效果。同時這也有利于我們區分出不同的班級。
```typescript
+++ b/first-app/src/app/mock-api/clazz.mock.api.ts
@@ -43,10 +43,10 @@ export class ClazzMockApi implements MockApiInterface {
for (let i = 0; i < size; i++) {
clazzes.push(new Clazz({
id: i,
- name: '班級',
+ name: '班級' + Math.floor(Math.random() * 100).toString(10),
teacher: new Teacher({
id: i,
- name: '教師'
+ name: '教師' + Math.floor(Math.random() * 100).toString(10),
})
}));
}
```
`Math.random()`會生成一個0至1之間的隨機值,該值與100相乘,會得到一個0-100內的隨機值,`Math.floor()`方法去除其小數部分,最后得到一個0至100間的整數,在整數上調用`toString(10)`方法將其轉換為字符串,期中`toString(10)`中的參數`10`表示轉換為10進制。如此以來,MockApi便可以返回一些更容易區分的模擬數據了。

| 名稱 | 鏈接 |
| -------- | ------------------------------------------------------------ |
| 本節源碼 | [https://github.com/mengyunzhi/angular11-guild/archive/step6.3.3.zip](https://github.com/mengyunzhi/angular11-guild/archive/step6.3.3.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 發布部署
- 第九章 總結