Angular HTTP Interceptor - Display spinner in multi-module app

后端 未结 4 1522
既然无缘
既然无缘 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:46

    For anyone who has the problem with the counter never reaching zero again, even though no requests are pending: I had to additionaly check for the type of event when increasing the counter:

     if (event instanceof HttpResponse) {
        this.counter.dec();
     } else {
        this.counter.inc();
     }
    

    Otherwise, i had the case of a HttpResponse also increasing my counter. With the above check my counter is going back to zero on all my components.

    Also, make sure a returning http error (e.g. 401) is also decreasing your counter, otherwise the counter will never reach zero again. To do so:

    return next.handle(req).pipe(tap(
      (event: HttpEvent) => {
        if (event instanceof HttpResponse) {
            this.counter.dec();
        }
      },
      err => {
        if (err instanceof HttpErrorResponse) {
          this.counter.dec();
        }
      }
    ));
    

提交回复
热议问题