关于 angular-interceptors
angular-interceptors 是面向 Angular 21 开发者的 HTTP 拦截器参考技能,介绍函数式拦截器及请求、响应、认证和错误处理模式。
主要功能
- 01使用 HttpInterceptorFn 创建函数式拦截器
- 02注册并排序拦截器
- 03添加认证请求头
- 04处理 HTTP 错误
- 05使用 HttpContext 设置请求标记
- 06转换请求与响应
适用场景
- 01为 HTTP 请求添加 Bearer 令牌
- 02收到 401 响应后重定向
- 03按请求设置缓存标记
- 04修改 API 请求或响应
安装
复制下面的命令,在终端中运行。
$
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 变更。
-
新增:函数式拦截器 — 使用
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