2016-02-28 155 views
1

我是rxjs的新手,我需要調用3個異步請求,這些請求以承諾開始,並按照調用順序將重新生成的對象放入數組中。這裏是一個我已經(部分基於this question):rxjs:鏈接異步請求

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

見http://stackoverflow.com/questions/35247310/angular-2-promise-all-with-rxjs/35247372#35247372 –

回答

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) 
});