Angular HTTP Interceptor - Display spinner in multi-module app

后端 未结 4 1526
既然无缘
既然无缘 2020-12-30 11:01

I\'m trying to display the ng4-loading-spinner spinner for HTTP calls made to my API.

I based my code on the examples in the following links:

4条回答
  •  清歌不尽
    2020-12-30 11:54

    forget reportProgress:true. The problem is that we have to discriminate the event of "do". Moreover, we must take a count of the calls, so the interceptor must be like

    contador: number = 0;
    
    intercept(req: HttpRequest, next: HttpHandler): Observable> {
            this.contador++;
            if (this.contador === 1) {
                this.spinner.show();
            }
            let handleObs: Observable> = next.handle(req);
            handleObs
            .catch((err: any) => { //If an error happens, this.contador-- too
                this.contador--;
                return Observable.throw(err);
            })
            .do(event => {
               if (event instanceof HttpResponse) { //<--only when event is a HttpRespose
                  this.contador--;
                  if (this.contador==0)
                     this.spinner.hide();
               }
            });
    
            return handleObs;
        }
    

提交回复
热议问题