目前,我正在尝试使用 Angular HttpInterceptor 显示一个微调器一次,因此每次 HttpRequest 完成时它都不会闪烁。我当前的 Interceptor.service.ts 代码如下所示:
@Injectable()
export class InterceptorService implements HttpInterceptor {
constructor(private spinnerService: SpinnerService) {}
showSpinner() {
this.spinnerService.show.next(true);
console.log('true');
}
hideSpinner() {
this.spinnerService.show.next(false);
console.log('false');
}
intercept(
req: HttpRequest<any>,
next: HttpHandler,
): Observable<HttpEvent<any>> {
const responseTimer$ = next
.handle(req)
.pipe(filter(e => e instanceof HttpResponse));
timer(300)
.pipe(takeUntil(responseTimer$))
.subscribe(() => this.showSpinner());
return next.handle(req).pipe(
tap(evt => {
if (evt instanceof HttpResponse) {
this.hideSpinner();
}
}),
);
}
}
但是如果我尝试这段代码,控制台会显示:
interceptor.service.ts:20 true
interceptor.service.ts:25 false
4 x interceptor.service.ts:20 true
4 x interceptor.service.ts:25 false
5 x interceptor.service.ts:25 false
interceptor.service.ts:25 false
但在我看来,它应该是 x 次为真,最后为假。我希望你能理解我想要实现的目标。
最佳答案
您的拦截器服务中需要一个计数器,它显示待处理请求的数量。当数字 >0 时,您会显示微调器。
编辑:
只是文本编辑器的理论
@Injectable()
export class InterceptorService implements HttpInterceptor {
pendingCount$: BehaviorSubject<number> = new BehaviorSubject(0);
constructor(private spinnerService: SpinnerService) {
this.pendingCount$.pipe(
map(Boolean),
distinctUntilChanged(),
).subscribe(
show => this.spinnerService.show.next(show),
);
}
intercept(
req: HttpRequest<any>,
next: HttpHandler,
): Observable<HttpEvent<any>> {
this.pendingCount$.next(this.pendingCount$.value++);
return next.handle(req).pipe(
tap(evt => this.pendingCount$.next(this.pendingCount$.value--)),
);
}
}
关于javascript - 延迟 Angular 旋转器不闪烁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59244649/