如何在拦截器中完成后等待响应

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

[我有拦截器。我想显示加载微调器,因此在我有订阅方法等待订阅完成的任何地方,请在那个时候以及完成隐藏该加载微调器的时候显示加载微调器。

如果我在每个组件中都这样做,那很容易并且可以正常工作。

ngOnInit() {
    this.spinnerService.show();
    this.service.methodName().subscribe(data => {
    },error => {
    },() => {
        this.spinnerService.hide();
    })
}

但是我如何在这个拦截器中做到这一点?使用此代码,仅在提出请求然后才执行disapperas时,显示微调器的时间很短。我的请求需要更长的时间...

 if (request.url.includes(this.apiUrl)) {
    this.spinnerService.show();
    let headers = new HttpHeaders();
    headers = headers.append('Content-Type', 'application/json');
    headers = headers.append('Authorization', `Bearer ${token}`);
    cloneRequest = request.clone({ headers: headers });
} else {
    cloneRequest = request.clone();
}
return next.handle(cloneRequest).pipe(map(response => {
            this.spinnerService.hide();
            return response;
        })).pipe(catchError(error => {
            let errorMessage = 'An unexpected error occured';
            if (error.error && error.error.message) {
                errorMessage = error.error.message;
            }
            // TODO: Error notifications are currently disabled.
            if (request.url.includes('login')) {
                this.notificationService.showError(errorMessage);
            }
            return throwError(error)
        }));
angular typescript interceptor
1个回答
0
投票

问题是您有多个API请求,因此即使第2个请求尚未完成,第一个请求完成后,它也会隐藏微调框。您可以在spinnerService上使用一个计数器:

@Injectable({
  providedIn: 'root'
})
export class SpinnerService {
  get shouldShow(): boolean {
    return !!this.count;
  }

  private count: number = 0; 

  show(): void {
    this.count++;
  }

  hide(): void {
    this.count = Math.max(0, this.count - 1);
  }
}

您必须更新拦截器来处理此问题,因为不显示微调框的api调用现在会减少微调框的数量。要对此进行调整,您应该检查它是否应该减少。同样,rxjs的finalize管道也是放置此类内容的理想场所:

const showSpinner = request.url.includes(this.apiUrl);

if (showSpinner) {
  this.spinnerService.show();

  cloneRequest = request.clone({ headers: new HttpHeaders({
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${token}`
  }) });
} else {
  cloneRequest = request.clone();
}

return next.handle(cloneRequest).pipe(
  catchError(error => //...),
  finalize(() => {
    if (showSpinner) {
      this.spinnerService.hide();
    }
  })
);
© www.soinside.com 2019 - 2024. All rights reserved.