【问题标题】:Conditionally replacing one http observable with another有条件地将一个 http observable 替换为另一个
【发布时间】:2017-06-19 20:08:51
【问题描述】:

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

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

【问题讨论】:

    标签: rxjs angular2-http


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2021-02-22
      • 1970-01-01
      • 2014-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多