上節的情況下,分別在班級管理、個人中心、注銷時發生了401錯誤。雖然我們可以在三個組件中分別加入判斷是否發生401錯誤的代碼,但這么做明顯是在造重復的輪子。
```typescript
this.httpClient.get(url)
.subscribe(() => console.log('success'),
error => 判斷是否發生了401,發生401則注銷應用,顯示登錄窗口);
```
## 再談攔截器
繼續開始之前,我們需要再復習下攔截器:

通過上圖不難發現,攔截器不但可以對請求進行攔截,還可以對后臺的響應進行攔截。
在前面的章節中,我們其實已經偷偷的說明了后期要加入一個登錄的攔截器了:

## 攔截異常
在`XAuthTokenInterceptor`中我們已經初步的掌握了使用`tap()`操作符對響應進行監聽的方法:
```typescript
return next.handle(request).pipe(tap(input => {
// 僅當input類型為HttpResponseBase,才嘗試獲取token并更新
if (input instanceof HttpResponseBase) {
const httpHeader = input.headers;
const xAuthToken = httpHeader.get('x-auth-token');
if (xAuthToken !== null) {
this.setToken(xAuthToken);
}
}
}));
```
本例中,我們將使用一個新的操作符`catchError()`來監聽后臺響應數據是否為**認證失敗**。
### 初始化
來到`src/app`文件夾,初始化`UnAuth`攔截器:
```bash
panjie@panjies-iMac app % pwd
/Users/panjie/github/mengyunzhi/angular11-guild/first-app/src/app
panjie@panjies-iMac app % ng g interceptor unAuth
CREATE src/app/un-auth.interceptor.spec.ts (417 bytes)
CREATE src/app/un-auth.interceptor.ts (411 bytes)
```
### 應用攔截器
有了攔截器后,我們將其添加到App模塊中以使其生效:
```typescript
+++ b/first-app/src/app/app.module.ts
@@ -16,6 +16,7 @@ import {XAuthTokenInterceptor} from './x-auth-token.interceptor';
import {WelcomeComponent} from './welcome.component';
import { NavComponent } from './nav/nav.component';
import {ApiInterceptor} from './api.interceptor';
+import {UnAuthInterceptor} from './un-auth.interceptor';
@NgModule({
@@ -39,7 +40,8 @@ import {ApiInterceptor} from './api.interceptor';
],
providers: [
{provide: HTTP_INTERCEPTORS, useClass: XAuthTokenInterceptor, multi: true},
- {provide: HTTP_INTERCEPTORS, useClass: ApiInterceptor, multi: true}
+ {provide: HTTP_INTERCEPTORS, useClass: ApiInterceptor, multi: true},
+ {provide: HTTP_INTERCEPTORS, useClass: UnAuthInterceptor, multi: true}
],
bootstrap: [IndexComponent]
})
```
### catchError
我們在編寫程序時會遇到異常,通常一些可見的異常使用`try catch`來解決。RxJS借鑒了這一思想。當數據流沒有按預期返回時,將向上拋出異常。打個現實生活中可能沒有的比方,我們關注了某個喜歡的人,此后我們將會收到該人發布的新狀態,但有一天這個不走尋常路是被人**發現**了,自此該賬號被永久封禁。在此事件中,這個永久封禁便是個異常事件。在該賬號被封的時候我們將得到一個某賬號被封的通知,這便是RxJS中的異常。
在Angular的Http請求中,將兩種情況視為異常:
1. 服務端的非2XX錯誤,比如資源未找到時發生的404錯語,用戶認證失敗時發生的401錯語,權限校驗時發生的403錯誤等。
2. 客戶端發生了網絡錯誤,比如當前計算機處理脫機狀態,無法訪問外部網絡;或是當前計算機的網卡因為驅動的問題而未正常工作等。
我們在此僅考慮第1種情況,服務端的非2xx錯誤。
與正常數據可以使用`tap()`監聽一樣,異常的數據可以`catchError()`操作符來監聽。與`tap()`操作符并不要求有返回值不同,`catchError()`操作符要求必須有返回值,該返回值可以通過`RxJS`提供的`throwError()`方法來快速實現:
```typescript
+++ b/first-app/src/app/un-auth.interceptor.ts
@@ -5,7 +5,8 @@ import {
HttpEvent,
HttpInterceptor
} from '@angular/common/http';
-import {Observable} from 'rxjs';
+import {Observable, throwError} from 'rxjs';
+import {catchError} from 'rxjs/operators';
@Injectable()
export class UnAuthInterceptor implements HttpInterceptor {
@@ -14,6 +15,11 @@ export class UnAuthInterceptor implements HttpInterceptor {
}
intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
- return next.handle(request);
+ return next.handle(request)
+ .pipe(catchError(error => { ①
+ console.log('發生了錯誤', error);
+ // 使用throwError()繼續向上拋出異常
+ return throwError(error); ②
+ }));
}
}
```
- ① `catchError`操作符同樣接收回調函數做為參數
- ② 使用`throwError()`方法向上繼續拋出異常
此時當點擊注銷時(需要按上節的步驟,模擬半個小時沒有登錄),將在控制臺中發現如下日志:

這其中的`status: 401`就是我們想要進行判斷的返回狀態碼。
```typescript
+++ b/first-app/src/app/un-auth.interceptor.ts
@@ -17,7 +17,9 @@ export class UnAuthInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
return next.handle(request)
.pipe(catchError(error => {
- console.log('發生了錯誤', error);
+ if (error.status === 401) {
+ console.log('發生了401錯誤, 通知應用顯示登錄界面', error);
+ }
// 使用throwError()繼續向上拋出異常
return throwError(error);
}));
```
此時一旦發生401錯誤,則會在控制臺中打印一條相關日志。401被判斷出來后,通知應用這個狀態則可以實現:當用戶因長時間未操作而發生被動注銷時,及時地顯示登錄界面了。
下一小節中,我們將建立一個服務,并將其分別注入到攔截器及`Index`組件,并以該服務為紐帶,在請求發生401時將通知發送給`Index`組件。
| 名稱 | 鏈接 |
| ------------ | ------------------------------------------------------------ |
| 處理請求錯誤 | [https://angular.cn/guide/http#handling-request-errors](https://angular.cn/guide/http#handling-request-errors) |
| 本節源碼 | [https://github.com/mengyunzhi/angular11-guild/archive/step6.7.1.zip](https://github.com/mengyunzhi/angular11-guild/archive/step6.7.1.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 發布部署
- 第九章 總結