Learning indications with the progress bar
Providing feedback to the user while performing actions when using web applications is one of the key aspects of a good user experience. A component like this helps users understand how long they need to wait and reduces uncertainty if the system is working. Progress bars can be also useful for gamification purposes, to make the overall UX more engaging and motivating.
How to do it…
In this recipe, we’ll simulate upload progress to the backend API by implementing a progress indicator that produces a random progress percentage until we get a response. If we still haven’t received a response after we get to the very end of the progress bar, we’ll set its progress to 95% and wait for the request to be completed.
Step 1 – Creating a progress loading stream
Inside our recipes.service.ts
service, we’ll start a stream of random numbers at a given interval. This will be stopped after we get a response from the backend:
private complete$ = new Subject<void>();
private randomProgress$ = interval(800).pipe(
map(() => Number((Math.random() * 25 + 5))),
scan((acc, curr) =>
+Math.min(acc + curr, 95).toFixed(2), 0),
takeUntil(this.complete$)
);
With the help of the scan
operator, we can decide whether we should produce the next increment of a progress percentage or whether we shouldn’t go over 95%.
Step 2 – Merging progress and request streams
Now, we can combine the randomProgress$
stream with the HTTP request and notify the progress indicator component whenever we get either random progress or complete the request:
postRecipe(recipe: Recipe): Observable<number> {
return merge(
this.randomProgress$,
this.httpClient.post<Recipe>(
'/api/recipes',
recipe
).pipe(
map(() => 100),
catchError(() => of(-1)),
finalize(() => this.unsubscribe$.next())
)
)
}
Once we call the postRecipe
service method inside a component, we can track the request progress:

Figure 2.4: Progress indicator
See also
- The
interval
function: https://rxjs.dev/api/index/function/interval - The
takeUntil
operator: https://rxjs.dev/api/operators/takeUntil - The
scan
operator: https://rxjs.dev/api/operators/scan - The
finalize
operator: https://rxjs.dev/api/operators/finalize - The
merge
operator: https://rxjs.dev/api/operators/merge