我正在尝试进行3个连续且异步(无并行)的请求,这些请求带有 HttpClient 和 Observable.forkJoin 。
到目前为止,这是它的外观,首先是 fileOperations 数组:
requestPayloadObjects:any[];//array of objects sent to the same request
//... after the array was built
this.requestPayloadObjects.forEach( ( payloadObject:any,i:number )=> {
//_uploadApi.postDoc returns an http observable
fileOperations.push( this._uploadApi.postDoc( payloadObject ) );
});
然后,当我有一系列可观察的对象后,我使用 Observable.forkJoin
// parallel subscriptions, all 3 observables are subscribed to asyncly
Observable.forkJoin(fileOperations).subscribe((res:any)=> {
// If all http calls succeeded you get here
},(err:any)=> {
// If 1 of all 3 that were sent failed you get here
});
但是我想要的是:
// NONE-parallel subscription
Observable.forkJoin(fileOperations).subscribe((res:any)=> {
// If all http calls succeeded you get here
},(err:any)=> {
// If 1 failed, you get here, but you do not send the others
});
我确定Observable.forkJoin不是实现此目的的Observable方法,而是什么? 我如何不进行并行订阅,只有前一个成功,才能继续进行下一个订阅? 使用Observables的正确方法是什么?
答案 0 :(得分:1)
我认为您正在寻找concatAll
。签出rxjs documentation。
答案 1 :(得分:0)
按照@MichaelKie的建议使用Observable.concat,我设法通过以下方式解决了此问题。
let requestPayloadObjects:any[] = [{...},{...},{...}];
let firstServerCall:Observable<any>;
this.requestPayloadObjects.forEach( ( payloadObject:any,i:number )=> {
let observable = this._uploadApi.postDoc(payloadObject:any);
if(i===0) {
firstServerCall = observable ;
}
else {
firstServerCall = firstServerCall.concat(observable );
};
});
firstServerCall.subscribe((res:any)=> {
// 1. will get here after every successful response
// 2. will continue on to send next http call after this
},(err:any)=> {
// will get here if subscription fails, without continuing to the next observable.
})