angular-interceptors について
angular-interceptorsは、Angular 21でHTTPインターセプターを実装する開発者向けのリファレンススキルです。関数型インターセプターの設定や、リクエスト、レスポンス、認証、エラー処理のパターンを扱います。
主な機能
- 01HttpInterceptorFnによる関数型設定
- 02インターセプターの登録と順序設定
- 03認証ヘッダーの追加
- 04HTTPエラーの処理
- 05HttpContextによるリクエストフラグ
- 06リクエストとレスポンスの変換
活用シーン
- 01HTTPリクエストへのBearerトークン追加
- 02401レスポンス後のリダイレクト
- 03リクエスト単位のキャッシュフラグ設定
- 04APIリクエストまたはレスポンスの変更
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ oguzhan18/ angular-ecosystem-skills --skill angular-interceptorsインストール後、Claude Code で/angular-interceptorsを入力して読み込まれたか確認します。
同梱ファイル
SKILL.md と一緒にインストールされる参考資料やスクリプト。
references/discussions/_INDEX.mdreferences/docs/_INDEX.mdreferences/issues/_INDEX.mdreferences/releases/_INDEX.md詳細
Angular HTTP インターセプター
バージョン: Angular 21(2025) タグ: HTTP、インターセプター、認証、ミドルウェア
参考資料: インターセプターガイド • API
API の変更点
このセクションでは、最近のバージョン固有の API の変更点について説明します。
-
新機能:関数型インターセプター — クラスベースの代わりに
HttpInterceptorFnを使用します -
新機能:withInterceptors を指定した provideHttpClient — 最新のインターセプター設定方法です
-
新機能:HttpContext — HttpContextToken を使用したリクエスト単位のメタデータです
-
非推奨:クラスベースの HttpInterceptor — 関数型への移行を推奨します
ベストプラクティス
- 関数型インターセプターを作成する
export const authInterceptor: HttpInterceptorFn = (req, next) => {
const authService = inject(AuthService);
const token = authService.getToken();
if (token) {
const authReq = req.clone({
setHeaders: { Authorization: `Bearer ${token}` }
});
return next(authReq);
}
return next(req);
};
- インターセプターを登録する
export const appConfig: ApplicationConfig = {
providers: [
provideHttpClient(
withInterceptors([authInterceptor, logInterceptor])
)
]
};
- インターセプターでエラーを処理する
export const errorInterceptor: HttpInterceptorFn = (req, next) => {
return next(req).pipe(
catchError((error: HttpErrorResponse) => {
if (error.status === 401) {
inject(Router).navigate(['/login']);
}
return throwError(() => error);
})
);
};
- 複数のインターセプターを使用する(順序が重要です)
provideHttpClient(
withInterceptors([loggingInterceptor, authInterceptor, errorInterceptor])
)
- リクエスト単位のフラグに HttpContext を使用する
const CACHE_KEY = new HttpContextToken<boolean>(() => false);
export const cacheInterceptor: HttpInterceptorFn = (req, next) => {
if (req.context.get(CACHE_KEY)) {
// Check cache
}
return next(req);
};
// Usage
http.get('/api/data', { context: new HttpContext().set(CACHE_KEY, true) });
- リクエストを変換する
export const transformInterceptor: HttpInterceptorFn = (req, next) => {
if (req.url.includes('/api/')) {
const transformed = req.clone({
setHeaders: { 'X-Custom-Header': 'value' }
});
return next(transformed);
}
return next(req);
};
- レスポンスを変換する
export const responseInterceptor: HttpInterceptorFn = (req, next) => {
return next(req).pipe(
map(event => {
if (event instanceof HttpResponse) {
return event.clone({ body: transformData(event.body) });
}
return event;
})
);
};
コメント
Markdown 対応