# AngularでAPIリクエスト前後の処理を共通化する
3 min read
Table of Contents
環境
node => v16.13.2angular => 15.0.4AngularでリクエストヘッダーにAuthorizationを共通して持たせたい
とかレスポンスのStatusCodeを見て共通処理を書くと言ったAPIリクエスト前後の処理をどこで実装するのがいいのか調べてみた。
HttpInterceptor
どうやらドンピシャっぽいのがこれで、ドキュメントによると
Intercepts and handles an HttpRequest or HttpResponse.
つまり、リクエストとレスポンスそれぞれに処理をできますよということ。まさに探していた機能に間違いない。
使ってみる
リクエストに対して処理をする
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest,} from "@angular/common/http";import { Injectable } from "@angular/core";import { Observable } from "rxjs";
@Injectable()export class AuthInterceptor implements HttpInterceptor { constructor() {} intercept( req: HttpRequest<any>, next: HttpHandler, ): Observable<HttpEvent<any>> { const newReq = req.clone({ headers: req.headers.set("Authorization", "Bearer " + "token"), }); // cloneされてヘッダーを付与したリクエストを次の処理に引き渡す return next.handle(newReq); }}これでリクエストヘッダーにBearer tokenというAuthorizationが付与されたうえでリクエストが投げられる。
レスポンスに対して処理をする
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest,} from "@angular/common/http";import { Injectable } from "@angular/core";import { Observable, catchError } from "rxjs";import { MatDialog } from "@angular/material/dialog";
@Injectable()export class ErrorInterceptor implements HttpInterceptor { constructor(public dialog: MatDialog) {} intercept( request: HttpRequest<any>, next: HttpHandler, ): Observable<HttpEvent<any>> { const req = request.clone(); return next.handle(req).pipe( catchError((res) => { if (400 <= res.status && res.status < 500) { console.log("400以上500未満のエラーが発生しました。"); }
return next.handle(req).pipe(); }), ); }}これでレスポンスのstatusが400以上500未満の場合に限りconsoleが発火するようになった。これを使用すれば各statusに対する共通の処理を書くことができる。
app.module.ts にプロバイダー登録
それぞれ処理を書いたらapp.module.tsのprovidersに登録する。
providers: [ { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }, { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true }, ],これで無事に求めている動きをするようになった。