mcmwhfy mcmwhfy - 3 years ago 173
TypeScript Question

Angular 4 show a loading gif for each http request

I'm quite new with angular 4 so what I need is to show a

each time when a http request is done.
so I have many components:


each one has a http request that get or save some data so when the hppt request is made I want to show my
component so I suppose is not a good practice injecting my loading component in each other component with a http request. Can I add a filter or something from angular that allows me to load the
component automatically in each component that has an http request ?

Also when the http request is done I want to show a message like "Done" or someting.

If anyone can provide me a solution for that I'll really appreciate, ty.

Answer Source

UPD: plunker. Take a look at app.ts. Sorry for having everything in a single file.

In Angular 4.3 there is a new HttpClientModule which supports interceptors. The main idea is to have something like this:

export class LoadingIndicatorService {

    private _loading: boolean = false;

    get loading(): boolean {
        return this._loading;

    onRequestStarted(): void {
        this._loading = true;

    onRequestFinished(): void {
        this._loading = false;

And then you just apply the logic from Christopher's answer to your HttpInterceptor.

The only thing you should be aware of are simultaneous request. This can be solved for example by generating a unique identifier to each request and storing it somewhere until the request is finished.

Then you can have a global LoadingIndicator component which injects LoadingIndicatorService.

For more details on HttpClientModule:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download