Loader Using HttpClient Interceptor Angular 4

浪子不回头ぞ 提交于 2019-11-30 22:39:44

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!