简体   繁体   中英

Loader in angular2 Http request

I want to show a loader when a http request

return this.http.get(this._apiUrl)
            //.map(res =><Location[]> res.json())
            .map(res => res.json())
            .filter(x => x.length > 0)
            .delay(5000)
            .catch(this.handleError);

in above code where I can specify a loader template ?

You must have read our conversation. If not, read it first. then you may try this solution.

You are going to return an observer . And I consider here that may be your fetch function is written in some external service .

fetch(){ 
return this.http.get(this._apiUrl) //.map(res => res.json()) .map(res => res.json()) .filter(x => x.length > 0) .delay(5000) .catch(this.handleError); 
}

So, I'd suggest to add it before you subscribe to an returned observer like this,

this.isLoading=true;
this.externalService.fetch.subscribe((result) =>{ 
                    this.result =result
                    },
                    (err)=>console.log(err),
                    ()=>{console.log("Done")
                          this.isLoading=false;
                    }); 

}

check this for reference http://plnkr.co/edit/UMMFk57seNrxqdgyeQIT?p=preview

Http itself doesn't provide any direct support for showing loaders.

Just set a field in your component or a service

fetchData() {
  this.isLoading = true;
  return this.http.get(this._apiUrl)
        //.map(res =><Location[]> res.json())
        .map(res => res.json())
        .filter(x => x.length > 0)
        .delay(5000)
        .catch(this.handleError)
        .do(this.isLoading = false);
}

Then bind the visibility of the loader to isLoading

<my-loader *ngIf="isLoading"></my-loader>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM