為了盡早的查看在真實后臺配合下的效果,我們在此進行集成測試。
## 設置路由
在整個項目中集成某個組件的方法是為該方法定制一個對應的路由。這樣一來Angular便可以根據瀏覽器URI地址來找到對應的組件。
在上個章節中,我們使用了惰性加載的方式加了班級模塊,這在生產項目中是非常有必要的。惰性加載避免了用戶啟動時過多的加載項目文件,增加了整個應用的啟動速度。在網絡不理想的情況下將大幅提升用戶的使用感受。
為此我們仍然使用惰性加載的方式來加載學生模塊的各個組件。
```typescript
+++ b/first-app/src/app/app-routing.module.ts
@@ -18,6 +18,10 @@ const routes: Routes = [
return m.ClazzModule;
})
},
+ {
+ path: 'student',
+ loadChildren: () => import('./student/student.module').then(m => m.StudentModule)
+ },
{
```
然后在`StudentModule`中進行相應的路由設置。
### 路由模塊
觀察App模塊與Clazz模塊的路由設置不難得出:App模塊使用了單獨的路由模塊`AppRoutingModule`,Clazz模塊直接將路由信息設置到了`ClazzModule`中。其實這兩種方式都是可以的,在實際的使用過程中,習慣于用哪種方式都可以,只需要保持整個項目的風格統一即可。
在此,我們展示如果手動在學生模塊中建立路由模塊,并將其應用到學生模塊中。
使用`shell`來到學生模塊所在文件夾,并執行如下命令:
```bash
panjie@panjies-iMac student % ng g m studentRouting --flat
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/student-routing.module.ts (200 bytes)
```
該命令將為我們當前文件夾下創建一個`student-routing.module.ts`文件:
```bash
panjie@panjies-iMac student % tree -L 1
.
├── add
├── student-routing.module.ts ??
├── student.component.css
├── student.component.html
├── student.component.spec.ts
├── student.component.ts
└── student.module.ts
```
文件內容如下:
```typescript
import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
@NgModule({
declarations: [],
imports: [
CommonModule
]
})
export class StudentRoutingModule {
}
```
接著將該文件內容修改為:
```typescript
import {NgModule} from '@angular/core';
import {Route, RouterModule} from '@angular/router';
import {StudentComponent} from './student.component';
import {AddComponent} from './add/add.component';
const routes = [
{
path: '',
component: StudentComponent
},
{
path: 'add',
component: AddComponent
}
] as Route[];
@NgModule({
imports: [
RouterModule.forChild(routes)
],
exports: [RouterModule]
})
export class StudentRoutingModule {
}
```
該模塊中的`imports`中引入了`RouterModule.forChild(routes)`,只所以能這樣使用是由于`forChild()`方法的返回值類型也相當于`RouterModule` 。如果直接`RouterModule`,則會得到一個空路由配置;但`forChild()`方法可以接收一個路由數組,該方法將返回一個具有路由配置的`RouterModule`。
該模塊接著在`exports`中聲明了`RouterModule`,其作用是將配置了路由的`RouterModule`拋出去(聲明為公有),這樣以來當其它模塊引入本模塊時,則相當于一并引入了配置了路由的`RouterModule`。
### `?`與`!`
現在執行`ng s`,將得到如下錯誤警告(針對增加學生組件):
```bash
Error: add/add.component.html:6:63 - error TS2531: Object is possibly 'null'.
6 <small class="text-danger" *ngIf="formGroup.get('name').invalid">
~~~~~~~
```
稍微翻譯一下得知它在告訴我們說:在執行`formGroup.get('name').invalid`由于`formGroup.get('name')`的值可以是`null`,所以有可能發生`在null上調用invalid屬性`的異常。
上述信息是Angular根據類型檢查為我們提示的錯誤,追其原由是由于我們在C層定義`formGroup`的類型是`FormGroup`,而`FormGroup`中的`get()`方法的返回值聲明如下(了解即可):
```typescript
/**
* Retrieves a child control given the control's name or path.
*
* @param path A dot-delimited string or array of string/number values that define the path to the
* control.
*
* @usageNotes
* ### Retrieve a nested control
*
* For example, to get a `name` control nested within a `person` sub-group:
*
* * `this.form.get('person.name');`
*
* -OR-
*
* * `this.form.get(['person', 'name']);`
*/
get(path: Array<string | number> | string): AbstractControl | null; ??
```
該方法聲明其返回值可能為`null`,這也是為什么Angular會出現上述提示的原因:既然`get()`的返回值可能為`null`,那么一旦其值為`null`則必然會發生在`null`上讀取`xxx`屬性的異常。雖然對當前學生新增組件而言,我們在C層的構造函數中對`formGroup`的各項進行了初始化從而避免執行`get()`方法時返回`null`,但這個邏輯對于Angular的語法檢查器而言太難了。Angular的語法檢查僅能夠做到根據返回值的類型進行推導(這已經很偉大了)。
此時我們有兩種方案來解決當前警告,第一種是使用`?`標識符,它表示:如果當前值是一個對象,則繼續執行;否則中斷執行:
```html
+++ b/first-app/src/app/student/add/add.component.html
@@ -3,7 +3,7 @@
<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 class="text-danger" *ngIf="formGroup.get('name')?.invalid">
名稱不能為空
</small>
</div>
@@ -11,11 +11,11 @@
<div class="mb-3 row">
<label class="col-sm-2 col-form-label">學號</label>
<div class="col-sm-10">
- {{formGroup.get('number').errors | json}}
+ {{formGroup.get('number')?.errors | json}}
<input type="text" class="form-control" formControlName="number">
- <small class="text-danger" *ngIf="formGroup.get('number').invalid">
- <span *ngIf="formGroup.get('number').errors.required">學號不能為空</span>
- <span *ngIf="formGroup.get('number').errors.numberExist">該學號已存在</span>
+ <small class="text-danger" *ngIf="formGroup.get('number')?.invalid">
+ <span *ngIf="formGroup.get('number')?.errors?.required">學號不能為空</span>
+ <span *ngIf="formGroup.get('number')?.errors?.numberExist">該學號已存在</span>
</small>
</div>
</div>
@@ -23,9 +23,9 @@
<label class="col-sm-2 col-form-label">手機號</label>
<div class="col-sm-10">
<input type="text" class="form-control" formControlName="phone">
- {{formGroup.get('phone').invalid}}
- {{formGroup.get('phone').errors | json}}
- <small class="text-danger" *ngIf="formGroup.get('phone').invalid">
+ {{formGroup.get('phone')?.invalid}}
+ {{formGroup.get('phone')?.errors | json}}
+ <small class="text-danger" *ngIf="formGroup.get('phone')?.invalid">
手機號格式不正確
</small>
</div>
```
第二種方式是使用`!`標識符,表示:我確認當前值必然是一個對象,請忽略掉對非object的判斷:
```typescript
+++ b/first-app/src/app/student/add/add.component.html
@@ -40,7 +40,7 @@
<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 class="text-danger" *ngIf="formGroup.get('clazzId')!.invalid">
必須選擇班級
</small>
</div>
```
在生產項目中,應該根據實際情況來決定是使用`?`還是`!`。以當前學生新增組件為例,在執行`formGroup.get('xxx')`應該返回一個對象,如果沒有對象返回的話就說明我們的C層代碼邏輯錯了(比如漏寫了),則此時應該使用`!`;而代碼`formGroup.get('number').errors.numberExist`中的`errors`則會在發生錯誤時才會有值,未發生錯誤的話其值則是`null`,此時則應該使用`?`標識符。
所以`formGroup.get('number').errors.numberExist`的正確寫法應當是`formGroup.get('number')!.errors?.numberExist`。
請按上述規范修正學生新增組件中的V層代碼。
### 引入路由
有了單獨的路由模塊后,便可以將其引入到學生模塊中了:
```typescript
+++ b/first-app/src/app/student/student.module.ts
@@ -5,6 +5,7 @@ import {ReactiveFormsModule} from '@angular/forms';
import { StudentComponent } from './student.component';
import {PageModule} from '../clazz/page/page.module';
import {RouterModule} from '@angular/router';
+import {StudentRoutingModule} from './student-routing.module';
@NgModule({
@@ -13,7 +14,8 @@ import {RouterModule} from '@angular/router';
CommonModule,
ReactiveFormsModule,
PageModule,
- RouterModule
+ RouterModule,
+ StudentRoutingModule
]
})
export class StudentModule {
```
路由引入完成后,打開瀏覽器并訪問[http://localhost:4200/student](http://localhost:4200/student)來檢驗下自己的成果吧。

### 設置菜單
最后我們完善下菜單,使得點擊“學生管理”時跳轉http://localhost:4200/student:
```html
+++ b/first-app/src/app/nav/nav.component.html
@@ -18,7 +18,7 @@
<a class="nav-link" routerLink="clazz">班級管理</a>
</li>
<li class="nav-item">
- <a class="nav-link" href="#">學生管理</a>
+ <a class="nav-link" routerLink="student">學生管理</a>
</li>
<li class="nav-item" routerLinkActive="active">
<a class="nav-link" routerLink="personal-center">個人中心</a>
```
## 測試
點擊新增按鈕后,將在控制臺得到以下信息:

其實該錯誤信息我們的IDE早早的就在提示我們:

產生該錯語的原因是由于當前模塊并不認識`app-clazz-select`選擇器。而產生該錯誤的原因是由于當前模塊并沒有引入`app-clazz-select`選擇器所在的模塊:
```typescript
+++ b/first-app/src/app/student/student.module.ts
@@ -6,6 +6,7 @@ import { StudentComponent } from './student.component';
import {PageModule} from '../clazz/page/page.module';
import {RouterModule} from '@angular/router';
import {StudentRoutingModule} from './student-routing.module';
+import {ClazzSelectModule} from '../clazz/clazz-select/clazz-select.module';
@NgModule({
@@ -15,7 +16,8 @@ import {StudentRoutingModule} from './student-routing.module';
ReactiveFormsModule,
PageModule,
RouterModule,
- StudentRoutingModule
+ StudentRoutingModule,
+ ClazzSelectModule
]
})
export class StudentModule {
```
引入模塊后錯誤消失(可能需要重啟`ng s`)。
接著進行新增功能的測試,發現點擊保存按鈕后控制臺雖然打印成功,但卻未進行跳轉,修正如下:
```typescript
+++ b/first-app/src/app/student/add/add.component.ts
@@ -3,6 +3,7 @@ import {FormControl, FormGroup, Validators} from '@angular/forms';
import {YzValidators} from '../../yz-validators';
import {YzAsyncValidators} from '../../yz-async-validators';
import {StudentService} from '../../service/student.service';
+import {ActivatedRoute, Router} from '@angular/router';
@Component({
selector: 'app-add',
@@ -12,7 +13,8 @@ import {StudentService} from '../../service/student.service';
export class AddComponent implements OnInit {
formGroup: FormGroup;
- constructor(private studentService: StudentService, private yzAsyncValidators: YzAsyncValidators) {
+ constructor(private studentService: StudentService, private yzAsyncValidators: YzAsyncValidators,
+ private router: Router, private route: ActivatedRoute) {
this.formGroup = new FormGroup({
name: new FormControl('', Validators.required),
number: new FormControl('', Validators.required, yzAsyncValidators.numberNotExist()),
@@ -34,7 +36,7 @@ export class AddComponent implements OnInit {
clazzId: number
};
this.studentService.add(student)
- .subscribe(success => console.log('保存成功', success),
+ .subscribe(success => this.router.navigate(['../'], {relativeTo: this.route}),
error => console.log('保存失敗', error));
}
```
跳轉修正后保存完學生后正常回跳到了學生列表界面。
隨后測試刪除、批量刪除、分頁功能等功能。

測試結果功能正常,集成測試結束。
## 本節資源
| 鏈接 | 名稱 |
| ------------------------------------------------------------ | -------- |
| [https://github.com/mengyunzhi/angular11-guild/archive/step7.6.zip](https://github.com/mengyunzhi/angular11-guild/archive/step7.6.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 發布部署
- 第九章 總結