Angular 17拦截器实现:独立应用(--standalone)注入失败求助
Angular 17独立应用拦截器注入与无限循环问题解决
问题根源
无限循环的核心原因几乎都是拦截器内部发起了HTTP请求,而该请求又被自身拦截。比如在AuthInterceptor中为了刷新token调用HttpClient,就会触发拦截逻辑,形成递归循环。
正确实现步骤
1. 调整拦截器依赖注入
不要直接注入HttpClient,改用HttpBackend来发起不经过拦截器的请求:
import { Injectable } from '@angular/core'; import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpBackend } from '@angular/common/http'; import { Observable } from 'rxjs'; import { HttpClient } from '@angular/common/http'; @Injectable() export class AuthInterceptor implements HttpInterceptor { // 用HttpBackend创建一个跳过拦截器的HttpClient实例 private readonly http: HttpClient; constructor(handler: HttpBackend) { this.http = new HttpClient(handler); } intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { // 先判断是否是需要跳过拦截的请求(比如token刷新接口) if (req.url.includes('/auth/refresh-token')) { return next.handle(req); } // 添加token到请求头 const authReq = req.clone({ setHeaders: { Authorization: `Bearer ${localStorage.getItem('token')}` } }); // 处理请求,这里如果需要刷新token,用this.http发起请求,不会触发拦截器 return next.handle(authReq); } }
2. 正确配置provideHttpClient
在独立应用的bootstrapApplication中配置时,确保withInterceptors正确引入拦截器:
import { bootstrapApplication } from '@angular/platform-browser'; import { provideHttpClient, withInterceptors } from '@angular/common/http'; import { AppComponent } from './app/app.component'; import { AuthInterceptor } from './app/interceptors/auth.interceptor'; bootstrapApplication(AppComponent, { providers: [ provideHttpClient(withInterceptors([AuthInterceptor])) ] });
3. 额外注意点
- 确保拦截器没有对所有请求都进行拦截处理,尤其是自身发起的请求要排除
- 如果使用了拦截器链,注意顺序是否合理
- 检查是否在拦截器中存在无限递归的逻辑(比如错误重试时没有终止条件)
内容的提问来源于stack exchange,提问作者Milton Isaya
相关产品推荐
相关产品推荐

