Search code examples
angularangular-http-interceptorsangular4-httpclient

Loader Using HttpClient Interceptor Angular 4


How can i implement a loader using Angular 4 HttpClient Interceptor? I have done the login and attaching the authorization header and i wonder if i can also do the "loader function" if some data is loading in the process? I would like to attached a icon loader that signals if some data is loading. Here's my authinterceptor below by the way.

export class GithubAuthInterceptor implements HttpInterceptor {
  intercept (req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const authReq = req.clone({
      headers: req.headers.set('Authorization', 'token')
    });
    return next.handle(authReq);
  }
}

Solution

  • Just for the sake of this question, I'm not going to go through creating a loader, and just talk about how you would implement an existing loader into the interceptor. Every time you make a call, the intercept() function is called. That means, at the beginning of the intercept() function, you should show a loader using an injected LoaderService whos job will be to show and hide a loader based on whether a call has been made and when it has been completed.

    constructor(private loaderService: LoaderService) {
    }
    
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
      this.loaderService.show();
      const authReq = req.clone({
        headers: req.headers.set('Authorization', 'token')
      });
      return next.handle(authReq);
    }
    

    Then, you have to make sure the loader is hidden after the call has been completed. You can do this with the do operator.

    return next.handle(authReq)
      .do(
      (response) => {
        if (response instanceof HttpResponse) {
          this.loaderService.hide();
        }
      },
      (error) => {
        this.loaderService.hide();
      });
    

    Make sure to import the do operator: import "rxjs/add/operator/do";

    Why do you have to check if (event instanceof HttpResponse)? This is because the HttpInterceptor intercepts ALL HttpEvents. This includes the HttpSentEvent, HttpProgressEvent, etc, but you don't want to hide the loader upon receiving those types of events. Only once you actually receive a response. And, of course, you will hide the loader if you receive an error. You can also put any other processes you may want to happen upon receive a response here in the do block. For example, storing an Auth token somewhere.

    For how to create your own loader, I have found an article that goes through the steps of creating and implementing a loader. You can use this as a guide to creating a loader. You can just ignore the parts about implementing it with a custom HttpService because you won't need that since you're using the new Angular HttpClient.