我是rxjs的新手,我需要调用3个异步请求,这些请求最初是作为promises,然后按照调用它们的顺序将重新转换的对象放入数组中。这就是我所拥有的(部分基于this question):
let observeFront = Observable.fromPromise(this.requestAsync(frontSlice, "front"));
let observeMiddle = Observable.fromPromise(this.requestAsync(midSlice, "middle"));
let observeEnd = Observable.fromPromise(this.requestAsync(endSlice, "end"));
let observeCombined = Observable.concat(observeFront, observeMiddle, observeEnd);
observeCombined.subscribe(data => {
// this logs only one object - need all 3 in proper order
console.log(data);
this.resultsEmitter.emit(data)
});
observeFront.subscribe(response => {
// logs the correct object
console.log("front result:", response);
});
observeMiddle.subscribe(response => {
// correct
console.log("middle result:", response);
});
observeEnd.subscribe(response => {
// correct
console.log("end result:", response);
});
如果我有[frontOb, middleObj, endObj]
?
答案 0 :(得分:1)
正如@Eric建议您可以使用forkJoin()
代替concat()
:
let observeFront = Observable.fromPromise(this.requestAsync(frontSlice, "front"));
let observeMiddle = Observable.fromPromise(this.requestAsync(midSlice, "middle"));
let observeEnd = Observable.fromPromise(this.requestAsync(endSlice, "end"));
let observeJoined = Observable.forkJoin(observeFront, observeMiddle, observeEnd);
observeJoined.subscribe(data => {
console.log(data); // => [frontOb, middleObj, endObj]
this.resultsEmitter.emit(data)
});