0

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 ?

1

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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>

10 Comments

Isn't it better to use before when you actually subscribe to an observer?
Thanks for the hint. I haven't encountered this operator yet. Do you have a link I couldn't find anything about it?
No I'm not talking about an operator. I'm talking about the place. When you subscribe to an observer you can use it before subscription or before when you call the service.
I see. Right. I don't use TS and Rx myself. Do you think it work to add a do(_ => this.isLoading = true) before http.get(). Like new Observable.of([1]).do(_ => this.isLoading = true).map(_ => this.http.get(...))...
plnkr.co/edit/UMMFk57seNrxqdgyeQIT?p=preview check this one by clicking friends tab.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.