0

I want to make one HTTP call, and then based on its results possibly replace it with another one. This is Angular.

this.http.get('foo.txt')
  .map(response => response.text())
  .if(text => text === "TRYAGAIN", 
    this.http.get('bar.txt').map(response => response.text()))
  .subscribe(text => console.log("got text", text);

But although there is an if operator, it does not seem to do what I want here.

I considered (mis)using errors to do this:

this.http.get('foo.txt')
  .map(response => response.text())
  .map(text => {
    if (text === "TRYAGAIN") throw "";
    return text;
  })
  .catch(err => this.http.get('bar.txt').map(response => response.text()))
  .subscribe(text => console.log("got text", text);

But this seems less than ideal as well. What is the correct idiom for handling this kind of situation?

1 Answer 1

2

You should use mergeMap (rxjs5) or flatMap (rxjs)

this.http.get('foo.txt')
  .map(response => response.text())
  .mergeMap(text => (text === 'TRYAGAIN' ?
    this.http.get('bar.txt').map(response => response.text())) :
    Observable.of(text))
  .subscribe(...)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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