【问题标题】:Delay spinner interceptor Angular延迟微调拦截器 Angular
【发布时间】:2020-05-24 14:13:21
【问题描述】:

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

但是有些网页请求比较快,这种情况下spinner会变成网页中的闪烁。

我想为微调器做一些延迟,但我不知道怎么做。

微调器组件

<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)
    );
  }

}

微调服务

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

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

}

微调器拦截器

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


    【解决方案1】:

    答案:https://codeburst.io/rxjs-show-spinner-for-a-minimum-amount-of-time-807ac6b23227

    另外,要实现相反的效果(如果请求很快,则根本不显示)查看race 运算符。

    【讨论】:

      【解决方案2】:

      你可以先在管道中使用 debounceTime rxjs 操作符,然后使用 finalize 方法。 例如。

          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();
                          }
                      })
                  );
      

      【讨论】:

        【解决方案3】:

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

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

        还有其他几种方法可以实现这一点,请参阅this answer

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2018-09-26
          • 2020-11-08
          • 2023-03-13
          • 2023-04-11
          • 2018-07-08
          • 2021-03-07
          • 1970-01-01
          相关资源
          最近更新 更多