新增課程時需要選擇綁定的班級,班級的個數可以是多個,此時適用于使用checkbox實現。為增加其復用性,本節將其直接打造為一個共享組件。并在課程新增中使用該組件完成班級的選擇。
# 功能開發
公用的組件加入到CoreModule中:
```
panjiedeMac-Pro:web-app panjie$ cd src/app/core/
panjiedeMac-Pro:core panjie$ ng g c multipleSelect
CREATE src/app/core/multiple-select/multiple-select.component.sass (0 bytes)
CREATE src/app/core/multiple-select/multiple-select.component.html (30 bytes)
CREATE src/app/core/multiple-select/multiple-select.component.spec.ts (685 bytes)
CREATE src/app/core/multiple-select/multiple-select.component.ts (305 bytes)
UPDATE src/app/core/core.module.ts (486 bytes)
```
## V層
src/app/core/multiple-select/multiple-select.component.html
```html
<div>
<label class="label" *ngFor="let data of list$? | async?">
<input type="checkbox"
(change)="onChange(data)?"> {{data.name}}
</label>
</div>
```
* ? 定義變量時以$結尾,表明該變量為一個可觀察(訂閱)的數據源
* ? angular提供的async管道實現了自動訂閱觀察的數據源
* ? checkbox被點擊時觸發change事件
>[success] async 管道會訂閱一個 Observable 或 Promise,并返回它發出的最近一個值。 當新值到來時,async 管道就會把該組件標記為需要進行變更檢測。當組件被銷毀時,async 管道就會自動取消訂閱,以消除潛在的內存泄露問題。
src/app/core/multiple-select/multiple-select.component.sass
```sass
label
margin-right: 1em
```
## C層
src/app/core/multiple-select/multiple-select.component.ts
```typescript
import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {Observable} from 'rxjs';
@Component({
selector: 'app-multiple-select',
templateUrl: './multiple-select.component.html',
styleUrls: ['./multiple-select.component.sass']
})
export class MultipleSelectComponent implements OnInit {
/** 數據列表 */
@Input()
list$: Observable<Array<{ name: string }>>;
/** 事件彈射器,用戶點選后將最終的結點彈射出去 */
@Output()
changed = new EventEmitter<Array<any>>();
constructor() {
}
/** 用戶選擇的對象 */
selectedObjects = new Array<any>();
ngOnInit() {
}
/**
* 點擊某個checkbox后觸發的函數
* 如果列表中已存在該項,則移除該項
* 如果列表中不存在該項,則添加該項
*/
onChange(data: any) {
let found = false;
this.selectedObjects.forEach((value, index) => {
if (data === value) {
found = true;
this.selectedObjects.splice(index, 1);
}
});
if (!found) {
this.selectedObjects.push(data);
}
this.changed.emit(this.selectedObjects);
}
}
```
## 單元測試
src/app/core/multiple-select/multiple-select.component.spec.ts
```typescript
import {async, ComponentFixture, fakeAsync, TestBed, tick} from '@angular/core/testing';
import {MultipleSelectComponent} from './multiple-select.component';
import {Subject} from 'rxjs';
import {Course} from '../../norm/entity/course';
import {By} from '@angular/platform-browser';
describe('MultipleSelectComponent', () => {
let component: MultipleSelectComponent;
let fixture: ComponentFixture<MultipleSelectComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [MultipleSelectComponent],
imports: []
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(MultipleSelectComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('數據綁定測試', () => { ?
const subject = new Subject<Course[]>();
component.list$ = subject.asObservable();
// 由于V層直接使用了異步async管道綁定的觀察者
// 所以在給C層對list$賦值后
// 使用detectChanges將此值傳送給V層
fixture.detectChanges();
// 當V層成功的綁定到數據源后,使用以下代碼發送數據,才能夠被V層接收到
subject.next([new Course({id: 1, name: 'test1'}),
new Course({id: 2, name: 'test2'})]);
fixture.detectChanges();
// 斷言生成了兩個label
const div = fixture.debugElement.query(By.css('div'));
expect(div.children.length).toBe(2);
});
it('點選測試', () => {
// 準備觀察者
const subject = new Subject<Course[]>();
component.list$ = subject.asObservable();
fixture.detectChanges();
// 發送數據
const course = new Course({id: 1, name: 'test1'});
subject.next([course]);
fixture.detectChanges();
// 獲取checkbox并點擊斷言
const checkBox: HTMLInputElement = fixture.debugElement.query(By.css('input[type="checkbox"]')).nativeElement as HTMLInputElement;
spyOn(component, 'onChange');
checkBox.click();
expect(component.onChange).toHaveBeenCalledWith(course);
});
it('onChange -> 選中', () => {
expect(component.selectedObjects.length).toBe(0);
const course = new Course();
component.onChange(course);
expect(component.selectedObjects.length).toBe(1);
expect(component.selectedObjects[0]).toBe(course);
});
it('onChange -> 取消選中', () => {
const course = new Course();
component.selectedObjects.push(course);
expect(component.selectedObjects.length).toBe(1);
component.onChange(course);
expect(component.selectedObjects.length).toBe(0);
});
it('onChange -> 彈射數據', () => {
let result: Array<any>;
component.changed.subscribe((data) => {
result = data;
});
const course = new Course();
component.onChange(course);
expect(result[0]).toBe(course);
});
});
```
在V中使用了async管道實現了自動訂閱數據源的功能。? 處對應的數據流大概如下:

# 參考文檔
| 名稱 | 鏈接 | 預計學習時長(分) |
| --- | --- | --- |
| 源碼地址 | [https://github.com/mengyunzhi/spring-boot-and-angular-guild/releases/tag/step6.1.3](https://github.com/mengyunzhi/spring-boot-and-angular-guild/releases/tag/step6.1.3) | - |
| AsyncPipe | [https://angular.cn/api/common/AsyncPipe](https://angular.cn/api/common/AsyncPipe) | 5 |
- 序言
- 第一章:Hello World
- 第一節:Angular準備工作
- 1 Node.js
- 2 npm
- 3 WebStorm
- 第二節:Hello Angular
- 第三節:Spring Boot準備工作
- 1 JDK
- 2 MAVEN
- 3 IDEA
- 第四節:Hello Spring Boot
- 1 Spring Initializr
- 2 Hello Spring Boot!
- 3 maven國內源配置
- 4 package與import
- 第五節:Hello Spring Boot + Angular
- 1 依賴注入【前】
- 2 HttpClient獲取數據【前】
- 3 數據綁定【前】
- 4 回調函數【選學】
- 第二章 教師管理
- 第一節 數據庫初始化
- 第二節 CRUD之R查數據
- 1 原型初始化【前】
- 2 連接數據庫【后】
- 3 使用JDBC讀取數據【后】
- 4 前后臺對接
- 5 ng-if【前】
- 6 日期管道【前】
- 第三節 CRUD之C增數據
- 1 新建組件并映射路由【前】
- 2 模板驅動表單【前】
- 3 httpClient post請求【前】
- 4 保存數據【后】
- 5 組件間調用【前】
- 第四節 CRUD之U改數據
- 1 路由參數【前】
- 2 請求映射【后】
- 3 前后臺對接【前】
- 4 更新數據【前】
- 5 更新某個教師【后】
- 6 路由器鏈接【前】
- 7 觀察者模式【前】
- 第五節 CRUD之D刪數據
- 1 綁定到用戶輸入事件【前】
- 2 刪除某個教師【后】
- 第六節 代碼重構
- 1 文件夾化【前】
- 2 優化交互體驗【前】
- 3 相對與絕對地址【前】
- 第三章 班級管理
- 第一節 JPA初始化數據表
- 第二節 班級列表
- 1 新建模塊【前】
- 2 初識單元測試【前】
- 3 初始化原型【前】
- 4 面向對象【前】
- 5 測試HTTP請求【前】
- 6 測試INPUT【前】
- 7 測試BUTTON【前】
- 8 @RequestParam【后】
- 9 Repository【后】
- 10 前后臺對接【前】
- 第三節 新增班級
- 1 初始化【前】
- 2 響應式表單【前】
- 3 測試POST請求【前】
- 4 JPA插入數據【后】
- 5 單元測試【后】
- 6 惰性加載【前】
- 7 對接【前】
- 第四節 編輯班級
- 1 FormGroup【前】
- 2 x、[x]、{{x}}與(x)【前】
- 3 模擬路由服務【前】
- 4 測試間諜spy【前】
- 5 使用JPA更新數據【后】
- 6 分層開發【后】
- 7 前后臺對接
- 8 深入imports【前】
- 9 深入exports【前】
- 第五節 選擇教師組件
- 1 初始化【前】
- 2 動態數據綁定【前】
- 3 初識泛型
- 4 @Output()【前】
- 5 @Input()【前】
- 6 再識單元測試【前】
- 7 其它問題
- 第六節 刪除班級
- 1 TDD【前】
- 2 TDD【后】
- 3 前后臺對接
- 第四章 學生管理
- 第一節 引入Bootstrap【前】
- 第二節 NAV導航組件【前】
- 1 初始化
- 2 Bootstrap格式化
- 3 RouterLinkActive
- 第三節 footer組件【前】
- 第四節 歡迎界面【前】
- 第五節 新增學生
- 1 初始化【前】
- 2 選擇班級組件【前】
- 3 復用選擇組件【前】
- 4 完善功能【前】
- 5 MVC【前】
- 6 非NULL校驗【后】
- 7 唯一性校驗【后】
- 8 @PrePersist【后】
- 9 CM層開發【后】
- 10 集成測試
- 第六節 學生列表
- 1 分頁【后】
- 2 HashMap與LinkedHashMap
- 3 初識綜合查詢【后】
- 4 綜合查詢進階【后】
- 5 小試綜合查詢【后】
- 6 初始化【前】
- 7 M層【前】
- 8 單元測試與分頁【前】
- 9 單選與多選【前】
- 10 集成測試
- 第七節 編輯學生
- 1 初始化【前】
- 2 嵌套組件測試【前】
- 3 功能開發【前】
- 4 JsonPath【后】
- 5 spyOn【后】
- 6 集成測試
- 7 @Input 異步傳值【前】
- 8 值傳遞與引入傳遞
- 9 @PreUpdate【后】
- 10 表單驗證【前】
- 第八節 刪除學生
- 1 CSS選擇器【前】
- 2 confirm【前】
- 3 功能開發與測試【后】
- 4 集成測試
- 5 定制提示框【前】
- 6 引入圖標庫【前】
- 第九節 集成測試
- 第五章 登錄與注銷
- 第一節:普通登錄
- 1 原型【前】
- 2 功能設計【前】
- 3 功能設計【后】
- 4 應用登錄組件【前】
- 5 注銷【前】
- 6 保留登錄狀態【前】
- 第二節:你是誰
- 1 過濾器【后】
- 2 令牌機制【后】
- 3 裝飾器模式【后】
- 4 攔截器【前】
- 5 RxJS操作符【前】
- 6 用戶登錄與注銷【后】
- 7 個人中心【前】
- 8 攔截器【后】
- 9 集成測試
- 10 單例模式
- 第六章 課程管理
- 第一節 新增課程
- 1 初始化【前】
- 2 嵌套組件測試【前】
- 3 async管道【前】
- 4 優雅的測試【前】
- 5 功能開發【前】
- 6 實體監聽器【后】
- 7 @ManyToMany【后】
- 8 集成測試【前】
- 9 異步驗證器【前】
- 10 詳解CORS【前】
- 第二節 課程列表
- 第三節 果斷
- 1 初始化【前】
- 2 分頁組件【前】
- 2 分頁組件【前】
- 3 綜合查詢【前】
- 4 綜合查詢【后】
- 4 綜合查詢【后】
- 第節 班級列表
- 第節 教師列表
- 第節 編輯課程
- TODO返回機制【前】
- 4 彈出框組件【前】
- 5 多路由出口【前】
- 第節 刪除課程
- 第七章 權限管理
- 第一節 AOP
- 總結
- 開發規范
- 備用