循环时按顺序获取可观察值?
Getting observable values in order when looping?
我很难弄清楚如何使用 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);
}
}
);
您可以使用 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)
}
我很难弄清楚如何使用 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);
}
}
);
您可以使用 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)
}