以下是一个示例代码,演示了如何在Angular拦截器中仅在第一个请求返回后发送后续请求。
首先,在您的应用程序中创建一个名为request-counter.interceptor.ts
的文件,其中包含以下代码:
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable, BehaviorSubject } from 'rxjs';
import { switchMap, filter, take } from 'rxjs/operators';
@Injectable()
export class RequestCounterInterceptor implements HttpInterceptor {
// 使用BehaviorSubject来跟踪请求计数器
private requestCounter$ = new BehaviorSubject(0);
intercept(request: HttpRequest, next: HttpHandler): Observable> {
// 增加请求计数器
this.requestCounter$.next(this.requestCounter$.value + 1);
// 如果是第一个请求,直接发送
if (this.requestCounter$.value === 1) {
return next.handle(request);
}
// 否则,等待第一个请求返回后再发送请求
return this.requestCounter$.pipe(
filter(counter => counter === 1), // 只接收值为1的计数器
take(1), // 只接收一个值
switchMap(() => next.handle(request)) // 发送请求
);
}
}
然后,在您的模块文件中(通常是app.module.ts
)注册拦截器,如下所示:
import { NgModule } from '@angular/core';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { RequestCounterInterceptor } from './request-counter.interceptor';
@NgModule({
imports: [HttpClientModule],
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: RequestCounterInterceptor, multi: true }
]
})
export class AppModule { }
现在,每次发送请求时,拦截器都会增加一个请求计数器。只有在第一个请求返回后,拦截器才会发送后续的请求。
请注意,此示例假设您已经设置了Angular的HTTP客户端,并且在模块文件中正确导入了HttpClientModule
。