Use Case: Parallel API Calls (Wait for All to Finish) in Angualr

 In Angular, to make multiple API calls in parallel and get their responses together, you typically use RxJS operators like forkJoincombineLatest, or zip, depending on your use case.

Use forkJoin when:

  • You want to fire multiple HTTP requests in parallel
  • You want to wait for all of them to complete
  • You want to get all the responses at once

🔧 Example: Parallel API Calls in Angular

1. Service: api.service.ts

@Injectable({
  providedIn: 'root'
})
export class ApiService {
  constructor(private http: HttpClient) {}

  getUsers(): Observable<any> {
    return this.http.get('https://jsonplaceholder.typicode.com/users');
  }

  getPosts(): Observable<any> {
    return this.http.get('https://jsonplaceholder.typicode.com/posts');
  }

  getComments(): Observable<any> {
    return this.http.get('https://jsonplaceholder.typicode.com/comments');
  }
}

2. Component: app.component.ts

import { Component, OnInit } from '@angular/core';
import { forkJoin } from 'rxjs';
import { ApiService } from './api.service';

@Component({
  selector: 'app-root',
  template: `<p>Check console for results</p>`
})
export class AppComponent implements OnInit {

  constructor(private apiService: ApiService) {}

  ngOnInit(): void {
    forkJoin({
      users: this.apiService.getUsers(),
      posts: this.apiService.getPosts(),
      comments: this.apiService.getComments()
    }).subscribe({
      next: (results) => {
        console.log('Users:', results.users);
        console.log('Posts:', results.posts);
        console.log('Comments:', results.comments);
      },
      error: (err) => console.error('Error:', err)
    });
  }
}

✅ Output

All 3 API calls are made in parallel, and forkJoin waits until all complete, then emits a single result object.


🔍 Alternative: combineLatest (if you need updates over time)

If your Observables emit multiple values over time, and you want to react when any one of them emits, use combineLatest.


🧠 Summary

OperatorUse Case
forkJoinOne-time parallel API calls, wait for all to complete
combineLatestContinuous stream, emits on any change
zipCombine values from multiple observables in order

Vikash Chauhan

C# & .NET experienced Software Engineer with a demonstrated history of working in the computer software industry.

Post a Comment

Previous Post Next Post

Contact Form