🚀Parallel API calls in Angular Applications

Tacettin Sertkaya
4 min readNov 27, 2023

--

To put it simply, collecting information for our apps one by one can be a slow process. However, with parallel API calls, it’s like having multiple helpers who can fetch different things all at the same time. As a result, our apps can run much faster, making our users happier.

Let’s make a sample project to better understand how will implement sequential and parallel API calls to observe practical differences.

Sequential API Call

Let’s begin by writing the code for our Sequential sample. We’ll use Dummyjson to mock our API and fetch data, as it provides realistic endpoints for testing. Here’s what our TypeScript file for the component will look like:

// sequential.component.ts

/**
* This function retrieves user data from the API.
* After successfully fetching the user data, it calls the `getUserCart` function with the user's id.
* If there's an error during the API call, it logs the error message.
*/
getUser() {
this.http.get(`${environment.BASE_URL}/users/1`)
.subscribe(
{
next: (data: any) => {
this.userData = data;
console.log('User Data', data)
this.getUserCart(data.id);
},
error: (err: any) => {
console.error('Error in User API call', err);
}
});
}

/**
* This function retrieves the cart data for a specific user from the API.
* After successfully fetching the cart data, it assigns the data to `this.cartData` and logs it.
* If there's an error during the API call, it logs the error message.
*
* @param userId - The ID of the user whose cart data is to be fetched.
*/
getUserCart(userId: number) {
this.http.get(`${environment.BASE_URL}/users/${userId}/carts`)
.subscribe(
{
next: (data: any) => {
this.cartData = data;
console.log('Cart Data', data)
},
error: (err: any) => {
console.error('Error in Cart API call', err);
}
});
}

Within this code, we have instructed our component to first retrieve user data and subsequently retrieve cart data once the post data has been successfully obtained.

Although this method is relatively simple, it has some drawbacks:

When we wait for the completion of the first call before making the second, it inevitably leads to a slower performance. Additionally, as we nest more calls within each other, the code becomes increasingly difficult to read, causing a decline in readability. Error handling also becomes more complicated when we have multiple nested calls, especially if any of them fail.

Parallel API Call

Let’s explore how to build the Parallel API Call Component in Angular, which allows us to send multiple requests simultaneously for increased efficiency.

Let’s start by leveraging a useful Angular tool called forkJoin to make parallel API calls. forkJoin is an RxJS operator that waits for Observables to complete and then combines the last values they emit. This means that you can use forkJoin to wait for multiple Observables to complete and then emit their latest values in the form of an array.

Here’s the code snippet for our ParallelComponent:

// parallel.component.ts

/**
* This function retrieves both user and cart data in parallel using the `forkJoin` method from RxJS.
* It makes two HTTP GET requests: one to fetch the user data and another to fetch the user's cart data.
* After successfully fetching the data, it assigns the data to `this.userData` and `this.cartData` respectively, and logs the data.
* If there's an error during the API calls, it logs the error message.
*/
getData() {
forkJoin({
postData: this.http.get(`${environment.BASE_URL}/users/1`),
userDate: this.http.get(`${environment.BASE_URL}/users/1/carts`)
}).subscribe({
next: (data: any) => {
this.userData = data.postData;
this.cartData = data.userDate;
console.log('User Data', data)
},
error: (err: any) => {
console.error('Error in User API call', err);
}
});
}

In this approach, forkJoin enables parallel API calls without waiting for the first call to complete before starting the next one.

Advantages of Using Parallel Approach Over Sequential Approach

Our app is designed to retrieve data quickly, without any delays. This means that you can access the information you need faster than ever before. The code has been improved in terms of readability by removing the nesting, making it cleaner and easier to understand.Error handling is simplified with forkJoin, allowing easy error detection across all calls.

When you run both SequentialComponent and ParallelComponent, you will observe that the latter fetches and displays data much faster. The reason behind this speed-up is that we do not have to wait for one task to complete before starting the next one, which highlights the efficiency of making parallel API calls.

Conclusion

We have examined how making one call at a time can cause us to slow down. It resembles standing in a lengthy line.We have examined how making one call at a time can cause us to slow down. It resembles standing in a lengthy line.

GitHub Link: https://github.com/tacettinsertkaya/ParallelAPICalls

--

--