Angular4: Using HttpClient's interceptor to se

2020-02-01 02:58发布

问题:

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

@Injectable()
export class ApiInterceptor implements HttpInterceptor {
    constructor(private _globalSpinnerService: GlobalSpinnerService) {}

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const spinnerParam: string = req.params.get("spinner")
        let handleObs: Observable<HttpEvent<any>> = next.handle(req)
        if(spinnerParam) {
            this._globalSpinnerService.spinner = true
            handleObs.toPromise().then(() => {
                this._globalSpinnerService.spinner = false
            })
        }

        return handleObs
    }
}

It's working as expected. However, I now see all my requests involving the spinner getting sent twice. So I guess my way to remove the spinner isn't the neatest. How can I tell my interceptor to remove my spinner once the handle is over ?

EDIT:

I changed the code by replacing my handleObs.toPromise().then by handleObs.do() and it's now working fine. I am just not sure why

回答1:

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;
}


标签: angular