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

问题描述 投票:1回答:1

我很难确定如何使用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个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.