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?
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(...)