我想进行一次HTTP调用,然后根据其结果将其替换为另一个。这是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);
但是虽然有一个if
运算符,但它似乎没有做我想要的。
我考虑过(误)使用错误来执行此操作:
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);
但这似乎也不太理想。处理这种情况的正确习惯是什么?
答案 0 :(得分:2)
您应该使用mergeMap
(rxjs5)或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(...)