angular 拦截器在 Http 请求数据响应之前完成

angular interceptor finalize before Http request data respond

这就是我实现拦截器以显示所有 Http 请求加载的方式。

 intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

       if(myCondition == true)
    {
        // my loading start showing here
        return next.handle(req).pipe(
        finalize(() => { 
                        // I hide my loading here 
                       })           );
    }
     return next.handle(req).pipe(
     finalize(() => { }));
    }

但是我的 Http 请求有很多数据,后端需要将近 10 秒才能完成。
我只需要在后端操作完成后隐藏加载即可。
但是,通过使用上面的代码,在后端完成之前加载是隐藏的。
我需要像 那样处理 HttpRespond 吗?

更新:
我找到了原因,我已经更新了我的代码。
我有一个条件"if(myCondition == true)",我只在条件为真时才显示加载。但是拦截方法必须有return,对吧?
所以我把 "return" 放在这个条件之外。
这 return 导致了问题,这就是加载消失的原因。
那么我该如何解决这种情况?

您在拨打 API 电话时需要管理某些场景。

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

            this.loadingService.show(); //Initiate loader

        return next.handle(req).do((event: HttpEvent<any>) => {
            if (event instanceof HttpResponse) {
                this.loadingService.hide();
                //Closing loader when you receive reponse
            }
        }, (err: any) => {
            if (err instanceof HttpErrorResponse) {
                this.loadingService.hide();
               //Closing loader when you have Error
            }
        })
    }

是的,你可以做到,有两种类型的拦截器,一种是 Request,另一种是 Response,所以在每个 Request 拦截器上我们开始加载,在每个 Response 我们隐藏加载的拦截器。

@Injectable()
export class AppHttpInterceptor implements HttpInterceptor {
    constructor() {}
intercept(
        req: HttpRequest<any>,
        next: HttpHandler
      ): Observable<HttpEvent<any>> {
        this.loadingService.show();
        return next.handle(req).pipe(
            tap(evt => {
                if (evt instanceof HttpResponse) {
                    if(evt != null) {
                          // here we are hide the loader flag
                          this.loadingService.hide();
                     }  
                }
            }),
            catchError((err: any) => {
                if(err instanceof HttpErrorResponse) {
                    try {
                         // if we are getting the erorr we also have to hide the loader 
                         this.loadingService.hide();                      
                    } catch(e) {
                       console.log(e)
                    }
                    //log error 
                }
            }));
      }
}