按由后到前的順序初始化如下:
## service
service/course.service.ts
```typescript
/**
* 分頁(yè)
* @param params name課程名稱(chēng) klassId 班級(jí) teacherId 教師
*/
page(params?: {name?: string, klassId?: number, teacherId?: number}): Observable<Page?> {
return null;
}
```
* ? 分頁(yè)信息屬于常用數(shù)據(jù)結(jié)構(gòu),自定Page類(lèi)以便復(fù)用。
## page
Page接口
```
panjiedeMac-Pro:norm panjie$ ng g class Page
CREATE src/app/norm/page.spec.ts (146 bytes)
CREATE src/app/norm/page.ts (22 bytes)
panjiedeMac-Pro:norm panjie$
```
參考學(xué)生管理中后臺(tái)返回的分頁(yè)數(shù)據(jù)初始化Page類(lèi)如下:
norm/page.ts
```typescript
/**
* 分頁(yè)數(shù)據(jù)
*/
export class Page<T?> {
/* 內(nèi)容 */
content: Array<T>?;
/* 總頁(yè)數(shù) */
totalPages: number;
constructor(params?: { content?: T, totalPages?: number }) {
if (params) {
if (params.content) {
this.content = params.content;
}
if (params.totalPages) {
this.totalPages = params.totalPages;
}
}
}
}
```
* ? 聲明Page具有容器的性質(zhì),可以裝入不同的對(duì)象
* ? 內(nèi)部容器,該類(lèi)型與Page類(lèi)型的泛型相同。
新建Page類(lèi)后在service/course.service.ts中引用Page并設(shè)置泛型。
service/course.service.ts
```typescript
import {Page} from '../norm/page'; ?
page(params?: {name?: string, klassId?: number, teacherId?: number}): Observable<Page<Course?>> {
return null;
}
```
* ? 引入Page類(lèi)型
* ? 聲明Page里裝入的對(duì)象類(lèi)型為Course
## ServiceStub
對(duì)應(yīng)在service的替身中增加page方法
service/course-stub.service.ts
```typescript
page(params?: {name?: string, klassId?: number, teacherId?: number}): Observable<Page<Course>> {
return null;
}
```
## 組件
在course中新建index組件:
```
panjiedeMac-Pro:course panjie$ ng g c index
CREATE src/app/course/index/index.component.sass (0 bytes)
CREATE src/app/course/index/index.component.html (20 bytes)
CREATE src/app/course/index/index.component.spec.ts (621 bytes)
CREATE src/app/course/index/index.component.ts (266 bytes)
UPDATE src/app/course/course.module.ts (761 bytes)
panjiedeMac-Pro:course panjie$
```
### V層初始化
course/index/index.component.html
```html
<form (ngSubmit)="onQuery()">
<label>課程名稱(chēng):<input name="name" [formControl]="params.name" type="text"/></label>
<label>教師:
<app-teacher-select (selected)="onSelectTeacher($event)"></app-teacher-select>
</label>
<label>班級(jí):
<app-klass-select (selected)="onSelectKlass($event)"></app-klass-select>
</label>
<button type="submit">查詢(xún)</button>
</form>
<div class="row">
<div class="col text-right">
<a class="btn btn-primary" routerLink="./add"><span class="oi oi-plus"></span>新增課程</a>
</div>
</div>
<table class="table">
<tr>
<th>序號(hào)</th>
<th>名稱(chēng)</th>
<th>任課教師</th>
<th>班級(jí)</th>
<th>操作</th>
</tr>
<tr *ngFor="let course of coursePage.content; index as index">
<td>{{index + 1}}</td>
<td>{{course.name}}</td>
<td>{{course.teacher.name}}</td>
<td>{{course.klass.name}}</td>
<td>
<a routerLink="./edit/{{course.id}}" class="btn btn-sm btn-info"><span class="oi oi-pencil"></span>編輯</a>
<button (click)="onDelete(course)" class="btn btn-sm btn-danger"><span class="oi oi-trash"></span>刪除</button>
</td>
</tr>
</table>
```
以下是分頁(yè)信息,暫時(shí)省略
### C層初始化
course/index/index.component.ts
```typescript
import {Component, OnInit} from '@angular/core';
import {Course} from '../../norm/entity/course';
import {Page} from '../../norm/page';
import {FormControl} from '@angular/forms';
import {Klass} from '../../norm/entity/Klass';
import {Teacher} from '../../norm/entity/Teacher';
@Component({
selector: 'app-index',
templateUrl: './index.component.html',
styleUrls: ['./index.component.sass']
})
export class IndexComponent implements OnInit {
params = {
name: new FormControl('')
};
coursePage: Page<Course>;
constructor() {
}
ngOnInit() {
}
onQuery() {
}
onSelectTeacher($event: Teacher) {
}
onSelectKlass($event: Klass) {
}
onDelete(course: Course) {
}
}
```
### 單元測(cè)試初始化
course/index/index.component.spec.ts
```typescript
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ IndexComponent ],
imports: [
ReactiveFormsModule, ?
FormsModule,?
TestModule ?
]
})
.compileComponents();
}));
```
* ? formControl指令
* ? (ngSubmit)方法
* ? app-teacher-select

單元測(cè)試提示不能解析app-klass-select。app-klass-select位于student模塊中的KlassSelect組件中。但由于歷史原因尚未生成KlassSelect組件對(duì)應(yīng)的測(cè)試替身。
## 遷移公共組件
我們之所以要將項(xiàng)目分成多個(gè)模塊,有一個(gè)重要的原因是為了:惰性加載。將項(xiàng)目分離成多個(gè)模塊可以將一個(gè)大型的項(xiàng)目分成多次被用戶(hù)加載。這樣可以使得一個(gè)較大的項(xiàng)目能夠有著比較良好的使用體驗(yàn)。而這一切的前提是:各個(gè)模塊互相獨(dú)立。如若在當(dāng)前Course模塊中使用位于Student模塊中的KlassSelect組件,則Course模塊產(chǎn)生了對(duì)Student模塊的依賴(lài),也就無(wú)法獨(dú)立于Student模塊存在了。在實(shí)際的生產(chǎn)項(xiàng)目中往往把一些公用的組件放到一個(gè)單獨(dú)的模塊中。為此將
Student模塊中的KlassSelect組件遷移到Core模塊中。
剪切

粘貼

然后將此組件添加到Core模塊的declarations中以及exports中,同時(shí)刪除原Student模塊declarations中對(duì)此組件的聲明。
core/core.modult.ts
```typescript
@NgModule({
declarations: [SelectComponent,
MultipleSelectComponent,
KlassSelectComponent?],
...
exports: [
SelectComponent,
MultipleSelectComponent,
KlassSelectComponent?
]
```
student/student.module.ts
```typescript
import { KlassSelectComponent } from '../core/klass-select/klass-select.component'; ?
@NgModule({
declarations: [AddComponent, KlassSelectComponent?, IndexComponent, EditComponent],
export class StudentModule {
}
```
### 新建組件測(cè)試替身
遷移完成后為其建立測(cè)試替身以便其被其它模塊使用時(shí)能夠優(yōu)雅的進(jìn)行單元測(cè)試。
```
panjiedeMac-Pro:core-testing panjie$ ng g c klassSelect -s -t --skip-tests
CREATE src/app/core/core-testing/klass-select/klass-select.component.ts (273 bytes)
UPDATE src/app/core/core-testing/core-testing.module.ts (562 bytes)
panjiedeMac-Pro:core-testing panjie$
```
初始化輸入、輸出并加入到測(cè)試控制器中:
```typescript
import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {Klass} from '../../../norm/entity/Klass';
import {CoreTestingController} from '../core-testing-controller';
@Component({
selector: 'app-klass-select',
template: `
<p>
klass-select works!
</p>
`,
styles: []
})
export class KlassSelectComponent implements OnInit {
@Output() selected = new EventEmitter<Klass>(); ?
@Input() klass: Klass; ?
constructor(private controller: CoreTestingController) {
this.controller.addUnit(this); ?
}
ngOnInit() {
}
}
```
* ? 對(duì)應(yīng)原組件的輸出
* ? 對(duì)應(yīng)原組件的輸入
* ? 添加到測(cè)試控制器中以便在單元測(cè)試中由測(cè)試控制器中獲取該組件
在測(cè)試模塊中將此組件替身輸出:
core/core-testing/core-testing.module.ts
```typescript
exports: [
MultipleSelectComponent,
KlassSelectComponent ?
],
...
export class CoreTestingModule { }
```
## 單元測(cè)試
準(zhǔn)備好測(cè)試組件替身后將CoreTestingModule開(kāi)入到課程列表組件測(cè)試文件中:
course/index/index.component.spec.ts
```typescript
imports: [
ReactiveFormsModule,
TestModule,
CoreTestingModule ?
]
```

```typescript
TestModule,
CoreTestingModule,
RouterTestingModule?
]
```
## V層中的?
引用了多個(gè)模塊后再次執(zhí)行單元測(cè)試,錯(cuò)誤如下:

此錯(cuò)誤在說(shuō):在undefined上讀取content時(shí)發(fā)生了錯(cuò)誤。此錯(cuò)誤產(chǎn)生的原因是由于在組件中使用了`xxxx.content`嘗試獲取數(shù)據(jù),但在執(zhí)行該語(yǔ)句時(shí)`xxxx`的值為undefined。
在組件的C層中并沒(méi)有讀取content屬性,所以錯(cuò)誤并不是在C層發(fā)生了。在V層中以content進(jìn)行搜索發(fā)現(xiàn)有以下語(yǔ)句:`<tr *ngFor="let course of coursePage.content; index as index">`。該錯(cuò)誤便是由此發(fā)生了。
這是由于:C層在初始化時(shí)只是聲明了coursePage的類(lèi)型,并未對(duì)其進(jìn)行初始化,所以coursePage當(dāng)前的值為undefined。在V層中嘗試執(zhí)行`coursePage.content`時(shí)便發(fā)生了`TypeError: Cannot read property 'content' of undefined`的錯(cuò)誤。解決該問(wèn)題的方法最少有兩種:由于V層的渲染操作發(fā)生在C層的ngOnInit方法以后,所以第一種方法可以在ngOnInit中對(duì)coursePage進(jìn)行初始化,此后在進(jìn)行V層的渲染時(shí)coursePage的值并不為undefined,當(dāng)然也就不會(huì)發(fā)生此錯(cuò)誤了;除此以外angular也充分地考慮到了此問(wèn)題,可以在V層中使用`?`來(lái)標(biāo)注某個(gè)變量以表示:當(dāng)此值為undefined時(shí)暫停渲染,當(dāng)此值不為undefined時(shí)繼續(xù)完成渲染。
course/index/index.component.html
```html
<tr *ngFor="let course of coursePage??.content; index as index">
```
* ? 在可能為undefined的變量后添加?以防止undefined錯(cuò)誤。
在渲染V層時(shí),除要規(guī)避在undefined上讀取某個(gè)屬性發(fā)生錯(cuò)誤以外,還要規(guī)避類(lèi)似的在null上讀取某個(gè)屬性發(fā)生錯(cuò)誤。而以下代碼則可能引發(fā)在null讀取某個(gè)屬性的錯(cuò)誤:
```html
<tr *ngFor="let course of coursePage.content; index as index">
<td>{{index + 1}}</td>
<td>{{course.name}}</td>
<td>{{course.teacher.name}}</td> ?
<td>{{course.klass.name}}</td>
<td>
```
* ? 在進(jìn)行數(shù)據(jù)表的設(shè)計(jì)時(shí),課程是可以不設(shè)置任課教師的,所以course.teacher的值可能為null。當(dāng)獲取的某個(gè)course沒(méi)有設(shè)置任課教師時(shí),則會(huì)發(fā)生在null讀取name屬性的錯(cuò)誤。
修正如下:
```html
<td>{{course.teacher?.name}}</td>
```
最終單元測(cè)試通過(guò):

# 修正其它測(cè)試
由于變更了KlassSelectComponent的位置以及所屬模塊所以必然會(huì)引起其它的單元測(cè)試錯(cuò)誤。逐個(gè)解決如下:
## 某組件同時(shí)存在于多個(gè)模塊中
```
student/AddComponent > should create
Failed: Type KlassSelectComponent is part of the declarations of 2 modules: CoreModule and DynamicTestModule! Please consider moving KlassSelectComponent to a higher module that imports CoreModule and DynamicTestModule. You can also create a new NgModule that exports and includes KlassSelectComponent then import that NgModule in CoreModule and DynamicTestModule.
```
在angular中某個(gè)組件不能同時(shí)存在于兩個(gè)模塊中(除非這兩個(gè)模塊不知道對(duì)方的存在)。這時(shí)由于在測(cè)試模塊(文件)中將KlassSelectComponent聲明到了declarations中。修正如下:
student/add/add.component.spec.ts
```typescript
declarations: [AddComponent, KlassSelectComponent?],
```
student/index/index.component.spec.ts
```typescript
declarations: [AddComponent, KlassSelectComponent?],
```
core/klass-select/klass-select.component.spec.ts
```typescript
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [KlassSelectComponent, SelectComponent??],
imports: [CoreModule??, HttpClientTestingModule]
})
```
* ? KlassSelectComponent依賴(lài)于原CoreModule的SelectComponent,此時(shí)兩個(gè)組件位于同一個(gè)模塊下,直接引用即可
* ? KlassSelectComponent當(dāng)前已經(jīng)屬于CoreModule,不能再進(jìn)行引用,否則將發(fā)生組件位于多模塊的錯(cuò)誤
最后加入其它依賴(lài):
```typescript
imports: [HttpClientTestingModule,
ReactiveFormsModule?]
})
```
單元測(cè)試整體通過(guò)。
# 參考文檔
| 名稱(chēng) | 鏈接 | 預(yù)計(jì)學(xué)習(xí)時(shí)長(zhǎng)(分) |
| --- | --- | --- |
| 源碼地址 | [https://github.com/mengyunzhi/spring-boot-and-angular-guild/releases/tag/step6.2.1](https://github.com/mengyunzhi/spring-boot-and-angular-guild/releases/tag/step6.2.1) | - |
| 安全導(dǎo)航運(yùn)算符( ? )和空屬性路徑 | [https://www.angular.cn/guide/template-syntax#the-safe-navigation-operator----and-null-property-paths](https://www.angular.cn/guide/template-syntax#the-safe-navigation-operator----and-null-property-paths) | 10 |
- 序言
- 第一章:Hello World
- 第一節(jié):Angular準(zhǔn)備工作
- 1 Node.js
- 2 npm
- 3 WebStorm
- 第二節(jié):Hello Angular
- 第三節(jié):Spring Boot準(zhǔn)備工作
- 1 JDK
- 2 MAVEN
- 3 IDEA
- 第四節(jié):Hello Spring Boot
- 1 Spring Initializr
- 2 Hello Spring Boot!
- 3 maven國(guó)內(nèi)源配置
- 4 package與import
- 第五節(jié):Hello Spring Boot + Angular
- 1 依賴(lài)注入【前】
- 2 HttpClient獲取數(shù)據(jù)【前】
- 3 數(shù)據(jù)綁定【前】
- 4 回調(diào)函數(shù)【選學(xué)】
- 第二章 教師管理
- 第一節(jié) 數(shù)據(jù)庫(kù)初始化
- 第二節(jié) CRUD之R查數(shù)據(jù)
- 1 原型初始化【前】
- 2 連接數(shù)據(jù)庫(kù)【后】
- 3 使用JDBC讀取數(shù)據(jù)【后】
- 4 前后臺(tái)對(duì)接
- 5 ng-if【前】
- 6 日期管道【前】
- 第三節(jié) CRUD之C增數(shù)據(jù)
- 1 新建組件并映射路由【前】
- 2 模板驅(qū)動(dòng)表單【前】
- 3 httpClient post請(qǐng)求【前】
- 4 保存數(shù)據(jù)【后】
- 5 組件間調(diào)用【前】
- 第四節(jié) CRUD之U改數(shù)據(jù)
- 1 路由參數(shù)【前】
- 2 請(qǐng)求映射【后】
- 3 前后臺(tái)對(duì)接【前】
- 4 更新數(shù)據(jù)【前】
- 5 更新某個(gè)教師【后】
- 6 路由器鏈接【前】
- 7 觀察者模式【前】
- 第五節(jié) CRUD之D刪數(shù)據(jù)
- 1 綁定到用戶(hù)輸入事件【前】
- 2 刪除某個(gè)教師【后】
- 第六節(jié) 代碼重構(gòu)
- 1 文件夾化【前】
- 2 優(yōu)化交互體驗(yàn)【前】
- 3 相對(duì)與絕對(duì)地址【前】
- 第三章 班級(jí)管理
- 第一節(jié) JPA初始化數(shù)據(jù)表
- 第二節(jié) 班級(jí)列表
- 1 新建模塊【前】
- 2 初識(shí)單元測(cè)試【前】
- 3 初始化原型【前】
- 4 面向?qū)ο蟆厩啊?/a>
- 5 測(cè)試HTTP請(qǐng)求【前】
- 6 測(cè)試INPUT【前】
- 7 測(cè)試BUTTON【前】
- 8 @RequestParam【后】
- 9 Repository【后】
- 10 前后臺(tái)對(duì)接【前】
- 第三節(jié) 新增班級(jí)
- 1 初始化【前】
- 2 響應(yīng)式表單【前】
- 3 測(cè)試POST請(qǐng)求【前】
- 4 JPA插入數(shù)據(jù)【后】
- 5 單元測(cè)試【后】
- 6 惰性加載【前】
- 7 對(duì)接【前】
- 第四節(jié) 編輯班級(jí)
- 1 FormGroup【前】
- 2 x、[x]、{{x}}與(x)【前】
- 3 模擬路由服務(wù)【前】
- 4 測(cè)試間諜spy【前】
- 5 使用JPA更新數(shù)據(jù)【后】
- 6 分層開(kāi)發(fā)【后】
- 7 前后臺(tái)對(duì)接
- 8 深入imports【前】
- 9 深入exports【前】
- 第五節(jié) 選擇教師組件
- 1 初始化【前】
- 2 動(dòng)態(tài)數(shù)據(jù)綁定【前】
- 3 初識(shí)泛型
- 4 @Output()【前】
- 5 @Input()【前】
- 6 再識(shí)單元測(cè)試【前】
- 7 其它問(wèn)題
- 第六節(jié) 刪除班級(jí)
- 1 TDD【前】
- 2 TDD【后】
- 3 前后臺(tái)對(duì)接
- 第四章 學(xué)生管理
- 第一節(jié) 引入Bootstrap【前】
- 第二節(jié) NAV導(dǎo)航組件【前】
- 1 初始化
- 2 Bootstrap格式化
- 3 RouterLinkActive
- 第三節(jié) footer組件【前】
- 第四節(jié) 歡迎界面【前】
- 第五節(jié) 新增學(xué)生
- 1 初始化【前】
- 2 選擇班級(jí)組件【前】
- 3 復(fù)用選擇組件【前】
- 4 完善功能【前】
- 5 MVC【前】
- 6 非NULL校驗(yàn)【后】
- 7 唯一性校驗(yàn)【后】
- 8 @PrePersist【后】
- 9 CM層開(kāi)發(fā)【后】
- 10 集成測(cè)試
- 第六節(jié) 學(xué)生列表
- 1 分頁(yè)【后】
- 2 HashMap與LinkedHashMap
- 3 初識(shí)綜合查詢(xún)【后】
- 4 綜合查詢(xún)進(jìn)階【后】
- 5 小試綜合查詢(xún)【后】
- 6 初始化【前】
- 7 M層【前】
- 8 單元測(cè)試與分頁(yè)【前】
- 9 單選與多選【前】
- 10 集成測(cè)試
- 第七節(jié) 編輯學(xué)生
- 1 初始化【前】
- 2 嵌套組件測(cè)試【前】
- 3 功能開(kāi)發(fā)【前】
- 4 JsonPath【后】
- 5 spyOn【后】
- 6 集成測(cè)試
- 7 @Input 異步傳值【前】
- 8 值傳遞與引入傳遞
- 9 @PreUpdate【后】
- 10 表單驗(yàn)證【前】
- 第八節(jié) 刪除學(xué)生
- 1 CSS選擇器【前】
- 2 confirm【前】
- 3 功能開(kāi)發(fā)與測(cè)試【后】
- 4 集成測(cè)試
- 5 定制提示框【前】
- 6 引入圖標(biāo)庫(kù)【前】
- 第九節(jié) 集成測(cè)試
- 第五章 登錄與注銷(xiāo)
- 第一節(jié):普通登錄
- 1 原型【前】
- 2 功能設(shè)計(jì)【前】
- 3 功能設(shè)計(jì)【后】
- 4 應(yīng)用登錄組件【前】
- 5 注銷(xiāo)【前】
- 6 保留登錄狀態(tài)【前】
- 第二節(jié):你是誰(shuí)
- 1 過(guò)濾器【后】
- 2 令牌機(jī)制【后】
- 3 裝飾器模式【后】
- 4 攔截器【前】
- 5 RxJS操作符【前】
- 6 用戶(hù)登錄與注銷(xiāo)【后】
- 7 個(gè)人中心【前】
- 8 攔截器【后】
- 9 集成測(cè)試
- 10 單例模式
- 第六章 課程管理
- 第一節(jié) 新增課程
- 1 初始化【前】
- 2 嵌套組件測(cè)試【前】
- 3 async管道【前】
- 4 優(yōu)雅的測(cè)試【前】
- 5 功能開(kāi)發(fā)【前】
- 6 實(shí)體監(jiān)聽(tīng)器【后】
- 7 @ManyToMany【后】
- 8 集成測(cè)試【前】
- 9 異步驗(yàn)證器【前】
- 10 詳解CORS【前】
- 第二節(jié) 課程列表
- 第三節(jié) 果斷
- 1 初始化【前】
- 2 分頁(yè)組件【前】
- 2 分頁(yè)組件【前】
- 3 綜合查詢(xún)【前】
- 4 綜合查詢(xún)【后】
- 4 綜合查詢(xún)【后】
- 第節(jié) 班級(jí)列表
- 第節(jié) 教師列表
- 第節(jié) 編輯課程
- TODO返回機(jī)制【前】
- 4 彈出框組件【前】
- 5 多路由出口【前】
- 第節(jié) 刪除課程
- 第七章 權(quán)限管理
- 第一節(jié) AOP
- 總結(jié)
- 開(kāi)發(fā)規(guī)范
- 備用