HttpInterceptor
===
https://wellwind.idv.tw/blog/2017/10/29/angular-advanced-handle-http-request-with-interceptor/
HttpInterceptor可以在HttpClient發生前攔截我們的request,讓我們可以傳回一個新的request,或針對response處理;偷看一下Angular的HttpClient原始碼可以發現,HttpClient的建構式本身就注入了一個HttpHandler,透過注入這個HttpHandler我們就能夠在request發生前處理些什麼事情:
```
export class HttpClient {
constructor(private handler: HttpHandler) {}
}
```
接著我們再來看看HttpInterceptor的程式碼:
```
export interface HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>;
}
```
其實就只是個介面而已,但我們可以透過實作intercept這個方法,來處理攔截後要做的事情,Angular已經內建了一個NoopInterceptor:
```
export const HTTP_INTERCEPTORS = new InjectionToken<HttpInterceptor[]>('HTTP_INTERCEPTORS');
@Injectable()
export class NoopInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req);
}
}
```
由於HttpInterceptor其實是個介面而已,轉換成JavaScript時不會產生任何的程式碼,因此Angular提供了InjectionToken來產生一個空的實體,才不會導致我們要設定相依注入時沒有東西可以注入(TypeScript的Interface對JavaScript等於沒有東西)
而NoopInterceptor則實作了HttpInterceptor介面,同時給了一個超簡單的程式碼,把原本送進來的request直接透過HttpHandler送出去而已!
所以當我們在Module中設定了HTTP_INTERCEPTORS要注入NoopInterceptor時,在每次HttpClient發生request之前就會來處理我們加入的intercept方法,並透過next.handle(someNewRequest)來得到新的request資訊!
{"metaMigratedAt":"2023-06-14T16:33:02.582Z","metaMigratedFrom":"Content","title":"HttpInterceptor","breaks":true,"contributors":"[]"}