本節我們嘗試一次刪除多個學生。
## 原型
在原型的,則一定要先開發原型!是新手我們應該這樣,是老手更應該這樣。
若要一次刪除多個學生,則需要為每條記錄前加一個checkbox選擇框。
```html
+++ b/first-app/src/app/student/student.component.html
@@ -7,6 +7,7 @@
<table class="table table-striped mt-2">
<thead>
<tr class="table-primary">
+ <th>選擇</th>
<th>序號</th>
<th>姓名</th>
<th>學號</th>
@@ -18,6 +19,7 @@
</thead>
<tbody>
<tr *ngFor="let student of pageData.content; index as index">
+ <td><input type="checkbox"></td>
<td>{{index + 1}}</td>
<td>{{student.name}}</td>
<td>{{student.number}}</td>
```

接著再增加一個刪除全部的按鈕:
```html
+++ b/first-app/src/app/student/student.component.html
@@ -1,6 +1,7 @@
<div class="row">
<div class="col-12 text-right">
<a class="btn btn-primary mr-2" routerLink="./add"><i class="fas fa-plus"></i>新增</a>
+ <button class="btn btn-danger mr-2" type="button"><i class="fas fa-trash-alt"></i>刪除</button>
</div>
</div>
```

## 功能
實現功能的方式有很多種,我們在此使用一個比較容易理解的。
- ①首先在C層中增加一個數組,用于存待刪除學生的**索引值**。注意,這里我們未使用`ID`,因為通過索引值能夠輕松的找到`ID`。
- ②某個`checkbox`并點擊時,將索引值傳給C層。C層根據索引在數組中查找,如果查到了,就將其由數組中刪除;如果沒有找到,就將其添加到數組中。
- ③點擊刪除按鈕時,如果待刪除的數組為空,則彈出提示框;如果數組不為空,則按索引值依次取出待刪除的ID,并將其傳入M層。
### ①初始化數組
```typescript
+++ b/first-app/src/app/student/student.component.ts
@@ -15,6 +15,8 @@ export class StudentComponent implements OnInit {
page = 0;
size = environment.size;
+ beDeletedIndexes = new Array<number>();
+
constructor(private studentService: StudentService) {
}
```
### ②傳值
```html
+++ b/first-app/src/app/student/student.component.html
@@ -20,7 +20,7 @@
</thead>
<tbody>
<tr *ngFor="let student of pageData.content; index as index">
- <td><input type="checkbox"></td>
+ <td><input type="checkbox" (click)="onCheckboxClick(index)"></td>
<td>{{index + 1}}</td>
<td>{{student.name}}</td>
<td>{{student.number}}</td>
```
C層:
```typescript
/**
* checkbox被點擊
* @param index 索引值
*/
onCheckboxClick(index: number): void {
if (this.beDeletedIndexes.indexOf(index) === -1) {
this.beDeletedIndexes.push(index);
} else {
this.beDeletedIndexes = this.beDeletedIndexes.filter(i => i !== index);
}
}
```
`filter()`是數組的一個內置方法,它的作用是將數組中的數據依次進行過濾,保留符合條件的,移除不符合條件的,比如:

上述方法的作用時將數據中的不等3的數據保留。
### ③點擊刪除按鈕
```html
- <button class="btn btn-danger mr-2" type="button"><i class="fas fa-trash-alt"></i>刪除</button>
+ <button class="btn btn-danger mr-2" type="button" (click)="onBatchDeleteClick()"><i class="fas fa-trash-alt"></i>刪除</button>
</div>
```
C層方法:
```typescript
+ /**
+ * 批量刪除按鈕被點擊
+ */
+ onBatchDeleteClick(): void {
+ if (this.beDeletedIndexes.length === 0) {
+ Report.warning('出錯啦', '請先選擇要刪除的學生', '返回');
+ }
+ }
}
```
- Report是notiflix提供的另一個方法,詳情請自行查閱官方文檔。

完成功能:
```typescript
+++ b/first-app/src/app/student/student.component.ts
onBatchDeleteClick(): void {
if (this.beDeletedIndexes.length === 0) {
Report.warning('出錯啦', '請先選擇要刪除的學生', '返回');
+ } else {
+ Confirm.show('請確認', '該操作不可逆', '確認', '取消',
+ () => {
+ // 根據index獲取ids
+ const ids = [] as number[];
+ this.beDeletedIndexes.forEach(index => {
+ ids.push(this.pageData.content[index].id);
+ });
+ // 調用批量刪除
+ this.studentService.batchDelete(ids)
+ .subscribe(() => {
+ this.beDeletedIndexes = [];
+ this.loadData(this.page);
+ });
+ });
}
}
}
```
最后,在M層初始化個方法,在方法中直接返回供開發用的可訂閱對象:
```typescript
+++ b/first-app/src/app/service/student.service.ts
@@ -47,4 +47,12 @@ export class StudentService {
.append('size', size.toString());
return this.httpClient.get<Page<Student>>('/student/pageOfCurrentTeacher', {params: httpParams});
}
+
+ /**
+ * 批量刪除
+ * @param ids 學生ID數組
+ */
+ batchDelete(ids: number[]): Observable<void> {
+ return of(undefined);
+ }
}
```
此時,點擊刪除按鈕時將彈出確認對話框,點擊確認后將觸發M層的方法。并在刪除成功后重新向后臺發起請求,獲取最新的分頁數據。

## M層
M層負責與API交互,批量刪除API如下:
```bash
DELETE /student/batchDeleteIds
```
接收的請求參數為:`ids`,類型為數組。
根據上述信息建立MockApi如下:
```typescript
+++ b/first-app/src/app/mock-api/student.mock.api.ts
@@ -70,6 +70,14 @@ export class StudentMockApi implements MockApiInterface {
}, {
method: 'DELETE',
url: '/student/(\\d+)'
+ }, {
+ method: 'DELETE',
+ url: '/student/batchDeleteIds',
+ result: ((urlMatches: any, options: RequestOptions) => {
+ const httpParams = options.params as HttpParams;
+ const ids = httpParams.getAll('ids');
+ Assert.isArray(ids, '未接收到ids');
+ })
}
];
}
```
單元測試:
```typescript
+ fit('batchDeleteIds', () => {
+ const ids = [1, 2, 3];
+ let called = false;
+ service.batchDelete(ids)
+ .subscribe(() => {
+ called = true;
+ });
+ expect(called).toBeFalse();
+ getTestScheduler().flush();
+ expect(called).toBeTrue();
+ });
+
```
完成方法:
```typescript
+++ b/first-app/src/app/service/student.service.ts
@@ -53,6 +53,7 @@ export class StudentService {
* @param ids 學生ID數組
*/
batchDelete(ids: number[]): Observable<void> {
- return of(undefined);
+ const stringIds = ids.map(id => id.toString());
+ return this.httpClient.delete<void>('/student/batchDeleteIds', {params: {ids: stringIds}});
}
}
```
繼`filter()`、`sort()`方法后,我們剛剛又使用了`map()`方法對數組中的各項進行了轉換。

單元測試通過,說明方法請求正確。
## 本節作業
Array中除`filter`、`map`外,還存在常用的`sort`等方法,請參閱官方文檔進一步學習。
| 鏈接 | 名稱 |
| ------------------------------------------------------------ | -------- |
| [https://github.com/mengyunzhi/angular11-guild/archive/step7.5.2.zip](https://github.com/mengyunzhi/angular11-guild/archive/step7.5.2.zip) | 本節源碼 |
| [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) | map() |
| [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) | sort() |
| [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) | filter() |
| [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) | Array |
- 序言
- 第一章 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 發布部署
- 第九章 總結