Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
677 views
in Technique[技术] by (71.8m points)

angular - Angular4: Using HttpClient's interceptor to setup a spinner

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...