How to take some actions while the response is pending in an http call in angular 2?

1.5k Views Asked by At

I have an http call which returns a response in sometime. While the response is pending i want to show a message to the user OR add a spinner which tells the user that the response is awaited.How can I do it in angular 2?

4

There are 4 best solutions below

0
On

I guess you will implement a Service (https://angular.io/docs/ts/latest/tutorial/toh-pt4.html) for this.

So there would be a function getData():

public getData(anyParam: any): Observable<any> {
  // start spinner !
  return this.http.get('anyUrl')
     .do(response => {
        // we are done! stop spinner !
     })
     .map(...);
}
0
On
_msgPopup.show("Wait while fetching data"); // Show popup
_http.get('anshumanpatil.com').subscribe(res=>{
    _msgPopup.hide(); //call ended
});
0
On

In HTML make some loader like this:

<div *nfIf="loader">
// some svg or whatever you want to represent loader
<div>

On HTTP call you make loading variable true and on response make it false.

public getData(anyParam: any): Observable<any> {
   this.loader = true;
   return this.http.get('anyUrl')
     .do(response => {
        // we are done! stop spinner !
        this.loader = false;
     })
     .map(...);
}
0
On

The solution to your problem is to declare a variable (or show a spinner, or anything) before launching your request, and then hide it when the request is done.

Your code would be something like:

this.isLoading = true;
this.get().finally(() => this.isLoading = false);

It will show it directly and then hide it, the next part is just handling the displaying with ngIf in your template.