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

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

这是我实现拦截器以显示所有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秒钟才能完成。我只需要在后端操作完成后隐藏加载即可。但是,通过使用上面的代码,在后端完成之前隐藏了加载。我是否需要像this example一样处理HttpRespond?

UPDATE:我找到了原因,并更新了代码。我有一个条件“ if(myCondition == true)”,仅在条件为真时才显示加载。但是我们必须对拦截方法有回报,对吗?因此,我将“返回”置于此条件之外。此返回导致问题,这就是加载消失的原因。那么如何解决这种情况?

angular angular-http-interceptors
2个回答
0
投票

[在进行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
            }
        })
    }

0
投票

是的,您可以执行两种拦截器类型,一种是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 
                }
            }));
      }
}
© www.soinside.com 2019 - 2024. All rights reserved.