基本的功能完成后,本節(jié)我們使用`ng s`進(jìn)行集成測(cè)試,在啟動(dòng)測(cè)試時(shí)將報(bào)一個(gè)錯(cuò)誤:
```bash
Error: src/app/student/edit/edit.component.ts:46:32 - error TS2345: Argument of type 'number | undefined' is not assignable to parameter of type 'number'.
Type 'undefined' is not assignable to type 'number'.
46 this.studentService.update(id, {
~~
```
`ng s`的啟動(dòng)的時(shí)候檢查出來(lái)一個(gè)錯(cuò)誤,這個(gè)錯(cuò)誤是在說(shuō):我們?cè)诮M件初始化的時(shí)候?qū)id`的類型定義成了`number | undefined`,而最終這個(gè)`id`卻做為參數(shù)傳給`this.studentService.update`。由于`studentService.update`方法中接收的第一參數(shù)類型被規(guī)定為`number`。所以最后實(shí)質(zhì)上相當(dāng)于把`'number | undefined'`類型賦值給了`number`類型,而這是不允許的。
為此我們應(yīng)當(dāng)如下對(duì)`onSubmit`方法進(jìn)行改進(jìn):
```typescript
+++ b/first-app/src/app/student/edit/edit.component.ts
@@ -39,11 +39,12 @@ export class EditComponent implements OnInit {
* @param id id
* @param formGroup 表單組
*/
- onSubmit(id: number, formGroup: FormGroup): void {
+ onSubmit(id: number | undefined①, formGroup: FormGroup): void {
const formValue = formGroup.value as { name: string, phone: string, email: string, clazzId: number };
Assert.isString(formValue.name, formValue.phone, formValue.email, '類型必須為字符串');
Assert.isNumber(formValue.clazzId, '類型必須為number');
- this.studentService.update(id, {
+ Assert.isNumber(id, 'id類型必須為number'); ②
+ this.studentService.update(id as number③, {
name: formValue.name,
email: formValue.email,
phone: formValue.phone,
```
①處對(duì)類型進(jìn)行統(tǒng)一,既然初始化的時(shí)候是`number | undefined`,那么我們這保持不變;③`studentService.update`既然只接收`number`,那么在傳值前我們可以使用`as`關(guān)鍵字來(lái)做類型指定;在類型指定前為了保證這樣的指定是沒(méi)有風(fēng)險(xiǎn)的,在進(jìn)行指定前對(duì)`id`進(jìn)行斷言。
## 增加路由
在`student`路由文件中增加編輯組件路由:
```typescript
+++ b/first-app/src/app/student/student-routing.module.ts
@@ -2,6 +2,7 @@ import {NgModule} from '@angular/core';
import {Route, RouterModule} from '@angular/router';
import {StudentComponent} from './student.component';
import {AddComponent} from './add/add.component';
+import {EditComponent} from './edit/edit.component';
const routes = [
{
@@ -11,6 +12,9 @@ const routes = [
{
path: 'add',
component: AddComponent
+ }, {
+ path: 'edit/:id',
+ component: EditComponent
}
] as Route[];
```
此時(shí)點(diǎn)擊編輯按鈕后將進(jìn)行正常的跳轉(zhuǎn),正常顯示組件。

編輯的學(xué)生內(nèi)容雖然可以正常顯示了,但保存按鈕卻是disabled狀態(tài)。這里由于我們?cè)诰庉嫿M件的學(xué)號(hào)字段上加入了`numberNotExist`驗(yàn)證器的原因:
```typescript
this.formGroup = new FormGroup({
name: new FormControl('', Validators.required),
number: new FormControl('', Validators.required, yzAsyncValidators.numberNotExist() ??),
phone: new FormControl('', YzValidators.phone),
email: new FormControl(),
clazzId: new FormControl(null, Validators.required)
});
```
在進(jìn)行學(xué)生編輯組件開(kāi)發(fā)時(shí),我們直接復(fù)制了新增學(xué)生的代碼,在復(fù)制代碼的同時(shí)其驗(yàn)證邏輯也跟著復(fù)制了過(guò)來(lái)。由于學(xué)生編輯組件并不涉及到學(xué)號(hào)的更新,所以學(xué)號(hào)上原本就不應(yīng)該設(shè)置驗(yàn)證器。
在設(shè)置`numberNotExist`情況下,后臺(tái)會(huì)以當(dāng)前學(xué)號(hào)做為條件查詢后臺(tái)是否存在有當(dāng)前學(xué)號(hào)的記錄。這當(dāng)然是存在的,該記錄就是當(dāng)前正在編輯的學(xué)生。
刪除學(xué)號(hào)上的驗(yàn)證器后保存按鈕生效:
```typescript
+++ b/first-app/src/app/student/edit/edit.component.ts
@@ -21,7 +21,7 @@ export class EditComponent implements OnInit {
console.log(this.activatedRoute);
this.formGroup = new FormGroup({
name: new FormControl('', Validators.required),
- number: new FormControl('', Validators.required, yzAsyncValidators.numberNotExist()),
+ number: new FormControl(''),
phone: new FormControl('', YzValidators.phone),
email: new FormControl(),
clazzId: new FormControl(null, Validators.required)
```

## 增加跳轉(zhuǎn)
最后增加保存成功后的跳轉(zhuǎn):
```typescript
+++ b/first-app/src/app/student/edit/edit.component.ts
@@ -2,7 +2,7 @@ import {Component, OnInit} from '@angular/core';
import {FormControl, FormGroup, Validators} from '@angular/forms';
import {YzValidators} from '../../yz-validators';
import {YzAsyncValidators} from '../../yz-async-validators';
-import {ActivatedRoute} from '@angular/router';
+import {ActivatedRoute, Router} from '@angular/router';
import {StudentService} from '../../service/student.service';
import {Assert} from '@yunzhi/ng-mock-api';
@@ -17,7 +17,8 @@ export class EditComponent implements OnInit {
constructor(private yzAsyncValidators: YzAsyncValidators,
private activatedRoute: ActivatedRoute,
- private studentService: StudentService) {
+ private studentService: StudentService,
+ private router: Router) {
console.log(this.activatedRoute);
this.formGroup = new FormGroup({
name: new FormControl('', Validators.required),
@@ -50,7 +51,7 @@ export class EditComponent implements OnInit {
phone: formValue.phone,
clazz: {id: formValue.clazzId}
}).subscribe(() => {
- console.log('更新成功');
+ this.router.navigate(['../../'], {relativeTo: this.activatedRoute});
});
}
```
集成測(cè)試完成。
## 參數(shù)快照
當(dāng)前我們?cè)讷@取路由中的參數(shù)ID時(shí),使用的由`snapshot`上讀取屬性的方法。`snapshot`的中文譯為快照,其中的照可以理解為照片。
為了把它稱為`snapshot`呢?是由于該數(shù)據(jù)一旦生成就不會(huì)改變,這就像照片一樣,一旦被拍了出來(lái)照片上的情景便會(huì)被留存下來(lái)。
為了更好的理解它,我們對(duì)當(dāng)前模塊中的路由做以下改動(dòng):
```typescript
+++ b/first-app/src/app/student/student-routing.module.ts
@@ -7,14 +7,16 @@ import {EditComponent} from './edit/edit.component';
const routes = [
{
path: '',
- component: StudentComponent
- },
- {
- path: 'add',
- component: AddComponent
- }, {
- path: 'edit/:id',
- component: EditComponent
+ component: StudentComponent,
+ children: [
+ {
+ path: 'add',
+ component: AddComponent
+ }, {
+ path: 'edit/:id',
+ component: EditComponent
+ }
+ ]
}
] as Route[];
```
即將添加組件、編輯組件放到列表組件的children中。然后對(duì)列表組件的V層中增加一個(gè)路由出口:
```html
+++ b/first-app/src/app/student/student.component.html
@@ -1,3 +1,4 @@
+<router-outlet></router-outlet>
<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>
```
此時(shí)當(dāng)我們?cè)趯W(xué)生列表中點(diǎn)擊編輯按鈕時(shí),將得到如下界面:

貌似一切都再正常不過(guò),但如果此時(shí)我們?cè)俅翁砑悠渌鼘W(xué)生對(duì)應(yīng)的編輯按鈕,則會(huì)發(fā)現(xiàn)除了瀏覽器`url`產(chǎn)生了變化以外,其它一切都沒(méi)有變化。

比如點(diǎn)擊第一個(gè)編輯按鈕時(shí),瀏覽器的地址為:`http://localhost:4200/student/edit/1`,當(dāng)擊第二個(gè)編輯按鈕時(shí),瀏覽器的地址為更為:`http://localhost:4200/student/edit/2`。除此以外,編輯組件顯示的學(xué)生并沒(méi)有任何變化。
這是由于Angular為了性能提升,在地址切換時(shí),將按以下規(guī)律來(lái)選擇是否構(gòu)造新組件:
當(dāng)瀏覽器地址由`http://localhost:4200/student/edit/1`變更為`http://localhost:4200/student/edit/2`時(shí),Angular發(fā)現(xiàn)變更前后的兩個(gè)地址對(duì)應(yīng)同一個(gè)路由,該路由指定了學(xué)生編輯組件,則Angular將選擇復(fù)用的以前的組件。
也就是說(shuō)瀏覽器的地址雖然變更了,但組件還是那個(gè)組件,并沒(méi)有發(fā)生任何變化。
而獲取編輯的學(xué)生信息的代碼位于學(xué)生編輯組件的`ngOnInit()`方法中,該方法僅會(huì)在組件實(shí)例化的時(shí)候被調(diào)用1次。所以上述事件的整個(gè)過(guò)程大體如下:
? 瀏覽器地址為`http://localhost:4200/student`時(shí),學(xué)生列表組件不存在,則初始化學(xué)生列表組件。該組件中的`ngOnInit`方法被自動(dòng)調(diào)用1次。
? 第1次點(diǎn)擊編輯按鈕時(shí),瀏覽器地址由`http://localhost:4200/student`跳轉(zhuǎn)至`http://localhost:4200/student/edit/1`,學(xué)生編輯組件不存在,則初始化學(xué)生編輯組件。該組件中的`ngOnInit`方法被自動(dòng)調(diào)用1次。
? 第2次點(diǎn)擊編輯按鈕時(shí),瀏覽器地址由`http://localhost:4200/student/edit/1`變更為`http://localhost:4200/student/edit/2`,學(xué)生編輯組件已存在,什么也不做。
當(dāng)學(xué)習(xí)一個(gè)偉大的框架時(shí),盡量不要懷疑框架的思想。比如我們前面遇到了問(wèn)題,首先想的是應(yīng)該如何改變自己的思想,讓自己的思想與Angular相一致。在這種情況下,再去思索解決問(wèn)題的方法。
Angular的思想是:如果我們想在路由改變時(shí)進(jìn)行一些操作,則應(yīng)該去訂閱路由信息。因?yàn)橐坏┪覀冇嗛喠寺酚尚畔?,路由發(fā)生變化時(shí)則會(huì)主通地通知我們。
下節(jié)中我們將使用**可訂閱的路由參數(shù)**來(lái)取替**路由參數(shù)快照**來(lái)解決當(dāng)前問(wèn)題。
## 資源鏈接
| 鏈接 | 名稱 |
| ------------------------------------------------------------ | -------- |
| [https://github.com/mengyunzhi/angular11-guild/archive/step7.7.4.zip](https://github.com/mengyunzhi/angular11-guild/archive/step7.7.4.zip) | 本節(jié)源碼 |
- 序言
- 第一章 Hello World
- 1.1 環(huán)境安裝
- 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 請(qǐng)求后臺(tái)數(shù)據(jù)
- 2.2.1 HttpClient
- 2.2.2 請(qǐng)求數(shù)據(jù)
- 2.2.3 模塊與依賴注入
- 2.2.4 異步與回調(diào)函數(shù)
- 2.2.5 集成測(cè)試
- 2.2.6 本章小節(jié)
- 2.3 新增教師
- 2.3.1 組件初始化
- 2.3.2 [(ngModel)]
- 2.3.3 對(duì)接后臺(tái)
- 2.3.4 路由
- 2.4 編輯教師
- 2.4.1 組件初始化
- 2.4.2 獲取路由參數(shù)
- 2.4.3 插值與模板表達(dá)式
- 2.4.4 初識(shí)泛型
- 2.4.5 更新教師
- 2.4.6 測(cè)試中的路由
- 2.5 刪除教師
- 2.6 收尾工作
- 2.6.1 RouterLink
- 2.6.2 fontawesome圖標(biāo)庫(kù)
- 2.6.3 firefox
- 2.7 總結(jié)
- 第三章 用戶登錄
- 3.1 初識(shí)單元測(cè)試
- 3.2 http概述
- 3.3 Basic access authentication
- 3.4 著陸組件
- 3.5 @Output
- 3.6 TypeScript 類
- 3.7 瀏覽器緩存
- 3.8 總結(jié)
- 第四章 個(gè)人中心
- 4.1 原型
- 4.2 管道
- 4.3 對(duì)接后臺(tái)
- 4.4 x-auth-token認(rèn)證
- 4.5 攔截器
- 4.6 小結(jié)
- 第五章 系統(tǒng)菜單
- 5.1 延遲及測(cè)試
- 5.2 手動(dòng)創(chuàng)建組件
- 5.3 隱藏測(cè)試信息
- 5.4 規(guī)劃路由
- 5.5 定義菜單
- 5.6 注銷(xiāo)
- 5.7 小結(jié)
- 第六章 班級(jí)管理
- 6.1 新增班級(jí)
- 6.1.1 組件初始化
- 6.1.2 MockApi 新建班級(jí)
- 6.1.3 ApiInterceptor
- 6.1.4 數(shù)據(jù)驗(yàn)證
- 6.1.5 教師選擇列表
- 6.1.6 MockApi 教師列表
- 6.1.7 代碼重構(gòu)
- 6.1.8 小結(jié)
- 6.2 教師列表組件
- 6.2.1 初始化
- 6.2.2 響應(yīng)式表單
- 6.2.3 getTestScheduler()
- 6.2.4 應(yīng)用組件
- 6.2.5 小結(jié)
- 6.3 班級(jí)列表
- 6.3.1 原型設(shè)計(jì)
- 6.3.2 初始化分頁(yè)
- 6.3.3 MockApi
- 6.3.4 靜態(tài)分頁(yè)
- 6.3.5 動(dòng)態(tài)分頁(yè)
- 6.3.6 @Input()
- 6.4 編輯班級(jí)
- 6.4.1 測(cè)試模塊
- 6.4.2 響應(yīng)式表單驗(yàn)證
- 6.4.3 @Input()
- 6.4.4 FormGroup
- 6.4.5 自定義FormControl
- 6.4.6 代碼重構(gòu)
- 6.4.7 小結(jié)
- 6.5 刪除班級(jí)
- 6.6 集成測(cè)試
- 6.6.1 惰性加載
- 6.6.2 API攔截器
- 6.6.3 路由與跳轉(zhuǎn)
- 6.6.4 ngStyle
- 6.7 初識(shí)Service
- 6.7.1 catchError
- 6.7.2 單例服務(wù)
- 6.7.3 單元測(cè)試
- 6.8 小結(jié)
- 第七章 學(xué)生管理
- 7.1 班級(jí)列表組件
- 7.2 新增學(xué)生
- 7.2.1 exports
- 7.2.2 自定義驗(yàn)證器
- 7.2.3 異步驗(yàn)證器
- 7.2.4 再識(shí)DI
- 7.2.5 屬性型指令
- 7.2.6 完成功能
- 7.2.7 小結(jié)
- 7.3 單元測(cè)試進(jìn)階
- 7.4 學(xué)生列表
- 7.4.1 JSON對(duì)象與對(duì)象
- 7.4.2 單元測(cè)試
- 7.4.3 分頁(yè)模塊
- 7.4.4 子組件測(cè)試
- 7.4.5 重構(gòu)分頁(yè)
- 7.5 刪除學(xué)生
- 7.5.1 第三方dialog
- 7.5.2 批量刪除
- 7.5.3 面向?qū)ο?/a>
- 7.6 集成測(cè)試
- 7.7 編輯學(xué)生
- 7.7.1 初始化
- 7.7.2 自定義provider
- 7.7.3 更新學(xué)生
- 7.7.4 集成測(cè)試
- 7.7.5 可訂閱的路由參數(shù)
- 7.7.6 小結(jié)
- 7.8 總結(jié)
- 第八章 其它
- 8.1 打包構(gòu)建
- 8.2 發(fā)布部署
- 第九章 總結(jié)