Mastering RxJS in Angular
A collection of code snippets relating to RxJS in Angular.
Published: 8/19/2024Simple Forkjoin#
private fetchMultiplePlantData$(ids: number[]): Observable<any[]> {
const requests = ids.map(id => this.fetchPlantData(id)); // Multiple individual requests
return forkJoin(requests); // Combine the requests into one observable
}
// Fetch a single plant data from the API by ID
private fetchPlantData$(id: number): Observable<any> {
return this.http.get<any>(`/api/plants/${id}`);
}
Also consider (for improved efficiency)#
Have the API handle a request for many ids in one batch
// Fetch plant data for multiple IDs from the API
private fetchBatchPlantData$(ids: number[]): Observable<any[]> {
return this.http.get<any[]>(`/api/plants?ids=${ids.join(',')}`);
}