Reputation: 1956
I'm trying to make a progress bar show for multiple requests done in an Angular application. I have gotten the multiple requests to work without the progress bar by using forkJoin, in short this is how I have done:
ArticleService
getArticles(articleIds: Array<string>) : Observable<any[]> {
let apiCalls = [];
articleIds.forEach(articleId => {
apiCalls.push(this.http.get(this.uri + '/article/' + articleId));
});
return forkJoin(apiCalls);
}
Component
let articleIds = ['234234', '2343334', '2354345'];
this.articleService.getArticles(articleIds).subscribe(response => {
response.forEach(responseObj => {
// Do stuff
});
});
But now I want to do something like in this example: https://www.learnrxjs.io/recipes/progressbar.html
But I'm not sure on how to set it up in my specific case, I have tried this:
ArticleService
getArticles(articleIds: Array<string>) : Observable<any[]> {
let apiCalls = [];
articleIds.forEach(articleId => {
apiCalls.push(this.http.get(this.uri + '/article/' + articleId));
});
return from(apiCalls).pipe(concatAll());
}
But not sure on how to setup it in the component to handle the progress update, preferably something that increments a "this.progress" variable on each completed request.
Anyone that has any ideas or pointers on how to do this? Should I use "switchMapTo" and where should I have that, in the service or component? Is there another better approach to handle this, can I tap into forkJoin to get events on each completed request to increment the progress bar?
Upvotes: 1
Views: 2335
Reputation: 11360
in a nutshell you can do something like below, using merge
you achieve the same effect as forkjoin i.e all run concurrently.
this.percentage = 0
let completed = 0
merge(...apiCalls).pipe(
tap(res=>this.percentage=(++completed/apiCalls.length))
)
Upvotes: 5