Httpinterceptor 加载屏幕

Httpinterceptor loading screen

我有一个 http 拦截器,除其他外,它会在处理 http 请求时打开和关闭加载覆盖。它通过激活在 app.component.ts 中订阅的共享服务来实现此目的,该服务实际上会切换 css.

问题在于,随着请求的进出,一个请求的覆盖关闭操作可能会关闭加载屏幕,而另一个请求仍在进行中。我明白为什么会这样,但我真的想不出解决这个问题的方法。

您可以使用数组来保存 "running jobs"。您的每个组件、服务可观察对象都可以作为唯一字符串 "key" 添加到服务中的数组中。


.
.
.
runningObservables: string[] = []
.
.
.
private addObservable(name: string) {
    this.runningObservables.push(name);
  }

  private removeObservable(name: string) {
    const index = this.runningObservables.indexOf(name);
    if (index > -1) {
      this.runningObservables.splice(index, 1);
    }
  }

然后在您的组件中使用类似的东西。

<app-spinner [isShown]="runningObservables.length > 0"></app-spinner>

在您的 subscrive/complete 方法中添加和删除条目。

observable 的简化版本。

this.addObservable('getChangeRequestTypes');
    this.changeRequestsService.getChangeRequestTypes()
      .subscribe(
        db => {
          this.removeObservable('getChangeRequestTypes');
          this.changeRequestTypes = db;
        },
        error => console.log(error),
        () => { });

一个简单的方法是使用 counter.

跟踪有多少请求未决

执行请求时增加计数器,当 HttpResponse 类型的响应到达时减少计数器。

当计数器达到 0 时,移除多余的,否则保留它直到达到值(达到值 0)。

Ps: 你可以把链接拦截器的完整代码作为例子。