仅当 api 调用时间超过 1 秒时才显示加载器

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

我已经尝试过,并且仍在尝试使用 rx 在 Angular 中创建一种机制来显示我的加载器,但前提是 API 调用长于 1 秒,如果更短,我不想显示它。

我尝试了很多不同的方法,但一直没能达到我所需要的。

我最接近的解决方案是在这种情况下:

        const apiCall = this.searchService
            .query(this.query)
            .pipe(finalize(()=> this.loading = false));

        timer(1000)
            .pipe(takeUntil(apiCall))
            .subscribe(()=> {
                this.loading = true;
            })

        apiCall.subscribe(result => {
            //do smth
        })

在这种情况下,加载器会在 API 请求完成后显示,但由于 Finalize 方法,它会立即消失(并且也会被调用两次)。

有人知道如何做这样的事情吗,因为我没有想法了?

angular rxjs rxjs6 angular-observable
1个回答
0
投票

我还没有测试你的代码,但我猜测你的代码会调用 api 两次,这就是它在第一次调用时删除加载程序而第二次调用根本不关心加载程序的原因。像这样的东西应该可以工作。

const apiObservable = this.searchService.
  .query(this.query).pipe(startWith(null));

const isLoadingObservable = timer(1000).pipe(
  map(() => true),
  startWith(false),
  take(2),
);

combineLatest(apiObservable, isLoadingObservable).pipe(
     tap(([resp, isLoading]) => this.isLoading = isLoading),
     filter(([resp, isLoading]) => resp !== null)
).subscribe(resp => {
  this.isLoading = false;
  //do smth
});
© www.soinside.com 2019 - 2024. All rights reserved.