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