一方面,我有一个逻辑,它发送多个HTTP请求并使用所有响应来计算其他一些值。为此,我正在使用forkJoin
基本上,我的代码看起来像这样:
const httpCalls = [];
//for iteration here obtaining the artist variable
httpCalls.push(this.http.get(this.apiUrl + '?method=artist.getsimilar&mbid=' + artist.mbid).map(res => res.json()).delay(i * 1000));
//after the for iteration
forkJoin(httpCalls).subscribe((similarResult : any) => {
for(let i = 0; i < similarResult.length; i++){
//and the rest of the code goes here
这很有效。
另一方面,我还希望在每个HTTP请求完成后递增加载进度条。只有在处理完所有请求后才会触发forkJoin,所以没有用。我需要确切知道每个HTTP请求何时完成。
我应该如何实现这一点,我还要考虑结合所有结果?
答案 0 :(得分:2)
您可以合并两个可观察对象,并通过merge
运算符接收各个通知。有关演示,请参阅this stackblitz。
merge(...httpCalls).subscribe(
res => { console.log("Received: " + res); },
error => { console.log("Error: " + error); },
() => { console.log("Complete!"); });
正如您在评论中提到的,如果必须按照与数组中的observable相同的顺序处理响应,则可以将observable与concat
运算符组合使用(请参阅this stackblitz):< / p>
concat(...httpCalls).subscribe(
res => { console.log("Received: " + res); },
error => { console.log("Error: " + error); },
() => { console.log("Complete!"); });