有条件地将一个 http observable 替换为另一个

Conditionally replacing one http observable with another

我想进行一个 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);

但这似乎也不理想。处理这种情况的正确成语是什么?

您应该使用 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(...)