延迟微调器拦截器角度

问题描述 投票:0回答:2

我为http请求制作了旋转器拦截器。对于每个http请求微调器都将显示。

但是某些Web请求相对较快,在这种情况下,微调器将在Web页面中闪烁。

我想让微调器有些延迟,但是我不知道怎么做。

Spin​​ner组件

<ng-container *ngIf="loading$ | async">
<mat-progress-bar  mode="indeterminate" color='warn'>
</mat-progress-bar>

export class SpinnerComponent implements OnInit {
  loading$;

  constructor(private spinnerService: SpinnerService) { }

  ngOnInit() {
    this.loading$ = this.spinnerService.isLoading$
    .pipe(
     delay(0)
    );
  }

}

Spin​​ner Service

export class SpinnerService {
isLoading$ = new Subject<boolean>();

show() {
    this.isLoading$.next(true);
}
hide() {
    this.isLoading$.next(false);
}

}

Spin​​ner Interceptor

export class SpinnerInterceptor implements HttpInterceptor {
requestCount = 0;
constructor(private spinnerService: SpinnerService) { }

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    this.requestCount++;
        this.spinnerService.show();

    return next.handle(request)
        .pipe(
            finalize(() => {
                this.requestCount--;
                if (this.requestCount === 0) {
                    this.spinnerService.hide();
                }
            })
        );
}

}

angular rxjs interceptor
2个回答
0
投票

您可以设置超时并在hide()函数中让代码在一段时间后执行。这是一个例子

     hide() {
       setTimeout( () => {     
        this.isLoading$.next(false);
       }, 2000 );
     }

还有其他几种方法可以实现,请参考this answer


0
投票

您可以在使用finalize方法之后先在管道内使用debounceTime rxjs运算符。例如

    import { debounceTime } from 'rxjs/operators';

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    this.requestCount++;
        this.spinnerService.show();

     return next.handle(request)
            .pipe(
                debounceTime(1000),
                finalize(() => {
                    this.requestCount--;
                    if (this.requestCount === 0) {
                        this.spinnerService.hide();
                    }
                })
            );
© www.soinside.com 2019 - 2024. All rights reserved.