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

时间:2020-03-12 10:47:52

标签: angular angular-http-interceptors

这是我实现拦截器以显示所有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?

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

2 个答案:

答案 0 :(得分:1)

在调用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
            }
        })
    }

答案 1 :(得分:1)

是的,您可以执行两种拦截器类型,一种是Request,另一种是Response,因此在每个Request拦截器上我们都开始加载,并且在每个{{1} }拦截器将隐藏该加载。

Response