Angular4: Using HttpClient's interceptor to setup a spinner

前端 未结 1 1652
孤城傲影
孤城傲影 2020-12-06 08:17

Here the interceptor I\'ve written to handle the spinner directly via the interceptor

@Injectable()
export class ApiInterceptor implements HttpInterceptor {
         


        
相关标签:
1条回答
  • 2020-12-06 08:36

    This happens because handleObs observable is cold, toPromise creates a subscription, then httpClient(...).subscribe creates another subscription. This results in several requests. And yes, handleObs.do() should be used instead, it doesn't result in subscription and just provides side effect.

    Generally it is desirable to have request counter for a spinner, because it should handle concurrent requests properly:

    function spinnerCallback() {
      if (globalSpinnerService.requestCount > 0) 
        globalSpinnerService.requestCount--;
    }
    
    if(spinnerParam) {
        globalSpinnerService.requestCount++;
        handleObs.do(spinnerCallback, spinnerCallback);
    }
    

    And globalSpinnerService.spinner is actually a getter:

    get spinner() {
      this.requestCount > 0;
    }
    
    0 讨论(0)
提交回复
热议问题