與路由參數(shù)快照只能獲取一次路由參數(shù)不同,可訂閱的路由參數(shù)可以在路由參數(shù)發(fā)生變更時(shí)時(shí)時(shí)的通知我們,路由參數(shù)每變化一次我們就會(huì)得到一個(gè)新的通知。
`ActivatedRoute`提供的`params`屬性具有上述特性,我們可以通過(guò)訂閱它來(lái)完成:當(dāng)路由參數(shù)發(fā)生變化時(shí)得到一個(gè)最新的通知。
## `ActivatedRoute.params`
在編輯組件中訂閱`ActivatedRoute.params`看看會(huì)發(fā)生什么:
```typescript
+++ b/first-app/src/app/student/edit/edit.component.ts
@@ -30,6 +30,9 @@ export class EditComponent implements OnInit {
}
ngOnInit(): void {
+ this.activatedRoute.params.subscribe(params => {
+ console.log('路由參數(shù)發(fā)生了變化', params);
+ });
this.id = +this.activatedRoute.snapshot.params.id;
Assert.isNumber(this.id, '接收到的id類型不正確');
this.loadData(this.id);
```
此時(shí):
? 瀏覽器地址為`http://localhost:4200/student`時(shí),學(xué)生列表組件不存在,則初始化學(xué)生列表組件。
? 第1次點(diǎn)擊編輯按鈕時(shí),瀏覽器地址由`http://localhost:4200/student`跳轉(zhuǎn)至`http://localhost:4200/student/edit/1`,學(xué)生編輯組件不存在,則初始化學(xué)生編輯組件。該組件中的`ngOnInit`方法被自動(dòng)調(diào)用1次。在該方法中對(duì)`ActivatedRoute.params`進(jìn)行訂閱,通過(guò)訂閱操作接收到了路由參數(shù)信息:

? 第2次點(diǎn)擊編輯按鈕時(shí),瀏覽器地址由`http://localhost:4200/student/edit/1`變更為`http://localhost:4200/student/edit/2`,學(xué)生編輯組件已存在,組件什么也不做。但由于在?中對(duì)路由參數(shù)進(jìn)行了訂閱,所以仍然可以在控制臺(tái)中打印最新的路由參數(shù)信息:

如此以來(lái),即使組件沒(méi)有重新初始化,我們?nèi)匀豢梢栽诼酚蓞?shù)發(fā)生變化時(shí)重新請(qǐng)求后臺(tái),進(jìn)而達(dá)到顯示待更新學(xué)生的目的:
```typescript
+++ b/first-app/src/app/student/edit/edit.component.ts
ngOnInit(): void {
this.activatedRoute.params.subscribe(params => {
console.log('路由參數(shù)發(fā)生了變化', params);
this.id = +params.id;
Assert.isNumber(this.id, '接收到的id類型不正確');
this.loadData(this.id);
});
}
```
此時(shí),無(wú)論我們?cè)趺袋c(diǎn)擊編輯按鈕,學(xué)生編輯組件都會(huì)根據(jù)最新的路由參數(shù)重新發(fā)起對(duì)后臺(tái)的數(shù)據(jù)請(qǐng)求,然后將請(qǐng)求的數(shù)據(jù)顯示在待學(xué)生更新組件上。
## 萬(wàn)物歸一
解決完上述BUG后,我們接著利用該思想繼續(xù)解決下一個(gè)BUG:
? 訪問(wèn)`http://localhost:4200/student`學(xué)生列表。
? 點(diǎn)擊編輯按鈕,編輯某個(gè)學(xué)生。
? 變更學(xué)生的基本信息后,點(diǎn)擊保存。
? 但是:原學(xué)生信息并未更新。
? 然而:刷新當(dāng)前界面后發(fā)生學(xué)生信息已更新。
其實(shí)這個(gè)BUG產(chǎn)生的原因與前面我們剛剛遇到的問(wèn)題完全一致。都是由于在路由跳轉(zhuǎn)時(shí)Angular檢測(cè)到了可以重復(fù)利用的組件,進(jìn)而沒(méi)有重新實(shí)例化新組件的造成的:
? 訪問(wèn)`http://localhost:4200/student`學(xué)生列表。
- 學(xué)生列表組件初始化,執(zhí)行1次`ngOnInit()`,在此方法中請(qǐng)求后臺(tái)數(shù)據(jù),使用后臺(tái)數(shù)據(jù)完成渲染,顯示學(xué)生列表。
? 點(diǎn)擊編輯按鈕,編輯某個(gè)學(xué)生。
- 學(xué)生列表組件已存在,復(fù)用原組件。
? 變更學(xué)生的基本信息后,點(diǎn)擊保存。
- 學(xué)生列表組件已存在,復(fù)用原組件。
? 但是:原學(xué)生信息并未更新。
- 學(xué)生列表組件并沒(méi)有感知到路由發(fā)生變化的能力,所以什么也不會(huì)做。
? 然而:刷新當(dāng)前界面后發(fā)生學(xué)生信息已更新。
- 重新實(shí)例化學(xué)生列表組件,執(zhí)行1次`ngOnInit()`,在此方法中請(qǐng)求后臺(tái)數(shù)據(jù),使用后臺(tái)數(shù)據(jù)完成渲染,顯示學(xué)生列表。
分析完組件的初始化過(guò)程后,解決的思路也有了:使學(xué)生列表組件感知到路由參數(shù)的變化。那么是否可以像`edit`組件一樣直接來(lái)訂閱`ActivatedRoute.params`呢?很遺憾,答案是否定的。
這是由于以下路由配置決定的:
```typescript
const routes = [
{
path: '',
component: StudentComponent,
?? children: [
{
path: 'add',
component: AddComponent
}, {
path: 'edit/:id',
component: EditComponent
}
]
}
] as Route[];
```
這個(gè)`children`意味著:無(wú)論是由`http://localhost:4200/student`跳轉(zhuǎn)到`http://localhost:4200/student/edit/1`;還是由`http://localhost:4200/student/edit/1`跳轉(zhuǎn)到`http://localhost:4200/student`。對(duì)于`StudentComponent`中的`ActivatedRoute.params`而言,均未發(fā)生變化。
總結(jié):訂閱`ActivatedRoute.params`無(wú)法感覺(jué)到路由在子路由及當(dāng)前路由間的跳轉(zhuǎn)。
這時(shí)候就需要請(qǐng)出`Router`這個(gè)大佬了。與`ActivatedRoute`不同,`Router`大佬可以感知到任何的路由事件,而不會(huì)局限在某一方面。
--------------------------------------**以下內(nèi)容了解即可**--------------------------------------
這時(shí)候我們可以這樣做:
```typescript
+++ b/first-app/src/app/student/student.component.ts
@@ -1,25 +1,44 @@
-import {Component, OnInit} from '@angular/core';
+import {Component, OnDestroy, OnInit} from '@angular/core';
import {Page} from '../entity/page';
import {Student} from '../entity/student';
import {StudentService} from '../service/student.service';
import {environment} from '../../environments/environment';
import {Confirm, Report} from 'notiflix';
+import {NavigationEnd, Router} from '@angular/router';
+import {filter} from 'rxjs/operators';
+import {Subscription} from 'rxjs';
@Component({
selector: 'app-student',
templateUrl: './student.component.html',
styleUrls: ['./student.component.css']
})
-export class StudentComponent implements OnInit {
+export class StudentComponent implements OnInit, OnDestroy {
pageData = {} as Page<Student>;
page = 0;
size = environment.size;
- constructor(private studentService: StudentService) {
+ /**
+ * 當(dāng)前組件所有的訂閱信息
+ */
+ subscriptions = new Array<Subscription>();
+
+
+ constructor(private studentService: StudentService,
+ private router: Router) {
}
ngOnInit(): void {
this.loadData(this.page);
+ this.subscriptions.push(this.router.events
+ .pipe(filter(e => e instanceof NavigationEnd))
+ .subscribe(event => {
+ event = event as NavigationEnd;
+ if (event.url === '/student') {
+ console.log('感知到了路由事件,重新請(qǐng)求數(shù)據(jù)');
+ this.loadData(this.page);
+ }
+ }));
}
/**
@@ -74,4 +93,11 @@ export class StudentComponent implements OnInit {
});
}
}
+
+ /**
+ * 生產(chǎn)項(xiàng)目中,應(yīng)該在組件銷毀時(shí),取消所有的訂閱
+ */
+ ngOnDestroy(): void {
+ this.subscriptions.forEach(s => s.unsubscribe());
+ }
}
```
該部分內(nèi)容有一定難度,超出了本教程(入門)的教學(xué)范圍,具體代碼功能不做解釋。
此時(shí),將編輯完某個(gè)學(xué)生信息后回跳到學(xué)生列表界面時(shí)數(shù)據(jù)便會(huì)重新請(qǐng)求1次。
**注意**:由于上述方法直接使用了`url`進(jìn)行判斷,這將導(dǎo)致其將隨著在生產(chǎn)環(huán)境中重新配置路由而失效。在生產(chǎn)環(huán)境中,應(yīng)該通過(guò)`service`來(lái)發(fā)送子組件的更新、新增事件,然后在學(xué)生列表組件中進(jìn)行訂閱。
^^^^^^^^^^^^^^^^^^^^^^^^^^以上內(nèi)容了解即可**^^^^^^^^^^^^^^^^^^^^^^^^^^
## 單元測(cè)試
功能實(shí)現(xiàn)后,再介紹下類似于這種**可訂閱的數(shù)據(jù)**應(yīng)該如何進(jìn)行單元測(cè)試,即在單元測(cè)試中如何給出一個(gè)**假的**可訂閱數(shù)據(jù)。
先啟動(dòng)學(xué)生編輯組件的單元測(cè)試:
```typescript
+++ b/first-app/src/app/student/edit/edit.component.spec.ts
@@ -31,7 +31,7 @@ describe('EditComponent', () => {
fixture.detectChanges();
});
- it('should create', () => {
+ fit('should create', () => {
expect(component).toBeTruthy();
});
```
錯(cuò)誤如下:

報(bào)錯(cuò)的原因是我們?cè)趩卧獪y(cè)試中沒(méi)能提供一個(gè)帶有可訂閱屬性`params`的`ActivatedRoute`,那么提供一個(gè)好了。
```typescript
+++ b/first-app/src/app/student/edit/edit.component.spec.ts
@@ -7,6 +7,7 @@ import {RouterTestingModule} from '@angular/router/testing';
import {ActivatedRoute, RouterModule} from '@angular/router';
import {ClazzSelectModule} from '../../clazz/clazz-select/clazz-select.module';
import {ReactiveFormsModule} from '@angular/forms';
+import {of} from 'rxjs';
describe('EditComponent', () => {
@@ -19,7 +20,12 @@ describe('EditComponent', () => {
ClazzSelectModule, ReactiveFormsModule],
declarations: [EditComponent],
providers: [
- {provide: ActivatedRoute, useValue: {snapshot: {params: {id: '123'}}}}
+ {
+ provide: ActivatedRoute,
+ useValue: {
+ params: of({id: '123'})①
+ }
+ }
]
})
```
① `of`函數(shù)可快速的提供一個(gè)可被訂閱的數(shù)據(jù)源。
① `of`函數(shù)接收任意類型,并將該值在被訂閱時(shí)發(fā)送出去,可以測(cè)試以下代碼:
```typescript
const a = of('123');
a.subscribe(s => console.log(s));
```
上述代碼我們使用`of`將`{id: '123'}`做為數(shù)據(jù)源發(fā)送給了訂閱者。此時(shí),當(dāng)在編輯組件中訂閱`ActivatedRoute.params`時(shí),則將得到`{id: '123'}`。編輯組件接收到`123`后,則會(huì)使用該`id`來(lái)請(qǐng)求數(shù)據(jù),近而完成待更新學(xué)生數(shù)據(jù)的展示:

此時(shí)當(dāng)點(diǎn)擊保存按鈕時(shí),則會(huì)發(fā)生如下異常:

這是由于此時(shí)編輯組件在更新成功后,執(zhí)行了如下代碼:
```typescript
this.router.navigate(['../../'], {relativeTo: this.activatedRoute});
```
### Router
由于我們并沒(méi)有聲明提供`Router`,所以此時(shí)組件中的`this.router`仍然為Angular提供的。此`router` 在進(jìn)行跳轉(zhuǎn)時(shí)需要依賴于直接的地址,而當(dāng)前單元測(cè)試并沒(méi)有這樣的環(huán)境,所以報(bào)出了上述異常。
解決該問(wèn)題的方法與解決可訂閱的路由參數(shù)的方法異曲同工:手動(dòng)提供一個(gè)`Router`。
```typescript
+++ b/first-app/src/app/student/edit/edit.component.spec.ts
@@ -4,7 +4,7 @@ import {EditComponent} from './edit.component';
import {MockApiTestingModule} from '../../mock-api/mock-api-testing.module';
import {getTestScheduler} from 'jasmine-marbles';
import {RouterTestingModule} from '@angular/router/testing';
-import {ActivatedRoute, RouterModule} from '@angular/router';
+import {ActivatedRoute, Router, RouterModule} from '@angular/router';
import {ClazzSelectModule} from '../../clazz/clazz-select/clazz-select.module';
import {ReactiveFormsModule} from '@angular/forms';
import {of} from 'rxjs';
@@ -25,6 +25,14 @@ describe('EditComponent', () => {
useValue: {
params: of({id: '123'})
}
+ },
+ {
+ provide: Router,
+ useValue: {
+ navigate: (...args: any) => {
+ console.log('調(diào)用了navigate方法', args);
+ }
+ }
}
]
})
```
此時(shí)在單元測(cè)試中再次點(diǎn)擊保存按鈕,則會(huì)在控制臺(tái)中打印一條信息:

學(xué)生編輯組件的單元測(cè)試完成后,將`fit`恢復(fù)為`it`,查看項(xiàng)目整體單元測(cè)試情況。
## ng t
錯(cuò)誤如下:

該錯(cuò)誤是由于單元測(cè)試未能提供`Router`造成的:
```typescript
+++ b/first-app/src/app/student/add/add.component.spec.ts
@@ -10,6 +10,7 @@ import {map} from 'rxjs/operators';
import {LoadingModule} from '../../directive/loading/loading.module';
import {randomString} from '@yunzhi/ng-mock-api/testing';
import {randomNumber} from '@yunzhi/ng-mock-api';
+import {RouterTestingModule} from '@angular/router/testing';
describe('student -> AddComponent', () => {
let component: AddComponent;
@@ -19,6 +20,7 @@ describe('student -> AddComponent', () => {
await TestBed.configureTestingModule({
declarations: [AddComponent],
imports: [
+ RouterTestingModule,
ReactiveFormsModule,
ClazzSelectModule,
MockApiTestingModule,
```
修正后錯(cuò)誤消失,好了,就到這里。
## 資源鏈接
| 鏈接 | 名稱 |
| ------------------------------------------------------------ | ------------- |
| [https://github.com/mengyunzhi/angular11-guild/archive/step7.7.5.zip](https://github.com/mengyunzhi/angular11-guild/archive/step7.7.5.zip) | 本節(jié)源碼 |
| [https://angular.cn/guide/dependency-injection-providers](https://angular.cn/guide/dependency-injection-providers) | DI提供者 |
| [https://angular.cn/api/router/NavigationEnd](https://angular.cn/api/router/NavigationEnd) | NavigationEnd |
| [https://cn.rx.js.org/class/es6/Observable.js~Observable.html#static-method-of](https://cn.rx.js.org/class/es6/Observable.js~Observable.html#static-method-of) | rxjs - of() |
- 序言
- 第一章 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 注銷
- 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é)