【问题标题】:Getting observable values in order when looping?循环时按顺序获取可观察值?
【发布时间】:2017-12-21 20:28:48
【问题描述】:

我很难弄清楚如何使用 Observables 按顺序打印用户。现在,这将根据请求的解决时间而无序打印。如何让它按顺序打印?

printUsersInOrder() {
  for (var i = 0; i < 10; i++) {
    this.getUser(i)
  }
}

// kibanaService uses angular2/http
getUser(userId: int) {
  this.kibanaService.getUser(userId).subscribe(
    res => {
      console.log(userId)
      console.log(res)
    },
    err => {
      console.log(err);
    }
  }
);

【问题讨论】:

标签: angular typescript observable angular2-services


【解决方案1】:

您可以使用combineLatest RxJs 流。

  printUsersInOrder() {
    let requests = [];
    let successfulResponses = []; // <-- Let's keep track of successful responses
    for (var i = 0; i < 10; i++) {
      requests.push(this.getUser(i).do(res => successfulResponses.push(res)))
    }

    Observable.combineLatest(requests)
    .subscribe((responses)=>{
        // response array will have the same order as it is in the requests array
        responses.map(res => console.log(res))
    }, (err) => {
        console.log(successfulResponses) // <--- This will print all successful responses
        console.log(err)
    })
  }

  // kibanaService uses angular2/http
  getUser(userId: int) {
    this.kibanaService.getUser(userId)
  }

有关combineLatest 的更多信息,您可以找到herehere

【讨论】:

  • 你知道如何捕捉异常吗?每当遇到错误时,combineLatest 就会退出。
  • 行在哪里:console.log(err) 写的。在那里你可以捕捉到错误。如果其中一个请求失败,则会调用错误回调。
  • 如果 4/5 的请求有效 - 我仍然想要 4 个有效的结果。现在,如果 4 个工作和 1 个失败,我将失去所有结果。知道该怎么做吗?
  • @sunflowerprincess 我已经更新了我的答案。希望它会有所帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-07
  • 2018-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-13
  • 1970-01-01
相关资源
最近更新 更多