Ambuj Khanna
Ambuj Khanna

Reputation: 1219

How to hide loader on all HTTP request completed in angular 4/6/7?

I want to show loader on any http request trigger and hide when all http requests are completed.

I am new to angular and I am not able to find a way to implement it.

Please help me!

Upvotes: 0

Views: 1081

Answers (2)

Roberc
Roberc

Reputation: 1956

Well, to make this happen you have to make few things:

  1. make global query injectable service which will serve your HTTP requests. add there the counter (it will increase by each request and will decrease after finishing)

For example:

@Injectable()
export class MyHTTPService {
public query(params: AjaxQueryClass) {
        ++this.requests_counter;
        return this.http.post(this.serverURI, JSON.stringify(params), { withCredentials: true})
        .toPromise()
        .then(d => {
                --this.requests_counter;
                return d;
            })
            .catch(err => {
                console.log(err);
                return new EmptyObservable();
            });

ok, you may use Observables, not Promises, but the idea should be clear - every request increases counter and it will stay on the screen until last request finishes. Use this service in every component and do server queries only with it.

  1. make transparent overlay with nice rolling animation and put it in the AppComponent (the main component) with this in the template:

<div id="overlay" *ngIf="counter == 0"></div>

  1. In the AppComponanet code there should be somewhere something like this:

    public counter = 0;
    ngDoCheck() {
       this.counter = this.my_http_service.requests_counter;
    }
    constructor(private my_http_service: MyHTTPService) {}

How to write CSS for transparent overlays, you'll find in the google. How to write injectables, you can find in the Angular Hero Tutorial.

Upvotes: 1

Eugene
Eugene

Reputation: 301

It depends on type of "loader" you want to do. If you implement HTTP requests with Observables, you can Subscribe to wait the result, at the same block - you can open the modal window (loading indication) or update your progress bar. After, using the .then() statement - close modal or put progress to 100% completion.

Everything is up to you and your vision.

Documentation: Angular Observables

At the same time, there are many similar questions already with some code and progress:

Upvotes: 0

Related Questions