Angular 2: HTTP preloaders

--

Some months ago, I wrote an article about HTTP Interceptor in new Angular. Which is useful for things like global HTTP headers, or calling of some 'middlewares'.

This is a real-world example of How to show preloader with every HTTP request through HTTP interceptor. A global solution for this problem is not anti-pattern from my point of view. We still can use a lot of various preloaders, not only one.

Example with 2 preloaders.

In this article I use an HTTP Interceptor from my previous article, for a complete understanding please read this article first.

Ok, now we are ready, let’s go!!

First, we define a component of large preloader.

And for small preloader.

Now we can create our PreloaderService, in which we define static variables of type Number for the large and small preloader. These we will modify through out public methods PreloaderService#showPreloader(type) and PreloaderService#hidePreloader(type). We can call them with parameter type which is a name of preloader which we can show or hide. In real world application, we can call a lot of request in the same time, but We can show preloader with start of the first request and hide it when the last request is done. This situation we can solve through our static variable which we have defined. The variable value we increase/decrease with every request. When is value 0, preloader is hidden.

Our PreloaderService we need add to a constructor in our HttpInterceptor service.

Now, we are ready to complete our example. We can add our preloaders to the right place in our application.

You can read & try all code in my GitHub repository.

Thanks for reading! 🐹🐯

--

--