In Angular, to make multiple API calls in parallel and get their responses together, you typically use RxJS operators like forkJoin
, combineLatest
, 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
Operator | Use Case |
---|---|
forkJoin | One-time parallel API calls, wait for all to complete |
combineLatest | Continuous stream, emits on any change |
zip | Combine values from multiple observables in order |
Tags
Angular