Making Parallel API Requests
In this use case, we assume our application will be performing an update of many users records in parallel. Of course this pattern can be used for any types of requests. We’ll first retrieve an array of user records and then perform many REST API calls simultaneously while handling errors from Alma.
We start by following the instructions in the “Adding additional routes” tutorial to add a new component and route called “parallel”. In our parallel.component.html file, we’ll create a simple button to run our example, and then a list of our users which will be updated as we retrieve the users.
In the parallel.component.ts file, we set up a
getUser function which returns a request for a user. In the function, we use the Rest Service, and pipe the result through two operators-
tap operator allows us to update a counter after each request is processed, which will help us later report on progress. The
catchError operator wraps any error we get from Alma and allows processing to continue. This is important since we don’t want to stop all processing if one request fails.
Next we create a
loadUsers function to do the bulk of the work. We first retrieve a list of users from Alma with the Get User API. Then we map the list of users through the
getUser function to set up the request. We then pipe the request array into the
forkJoin function which makes the requests in parallel. The result is an array of user objects (or errors). We can then handle each response, whether it is an error or success.
As our test runs, we see the list being populated. We can also see the error handling, which in this case is a simple log to the Console.
We’ve included a check box in the template which controls whether we show progress. The check box sets the mode property on the progress spinner. If the mode is set to determinate, the value is calculated via a
percentComplete property which calculates the number of processed records as a percentage of the total number of requests to be made. Then when we run the code, the progress spinner fills as the requests are processed.
Using these patterns allows us to easily make parallel API calls to Alma in a controlled way and provide a responsive experience for our users.