在循环时按顺序获取可观察值?

时间:2017-12-21 20:28:49

标签: angular typescript observable angular2-services

我很难确定如何使用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);
    }
  }
);

1 个答案:

答案 0 :(得分:2)

您可以使用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