-
-
Save robertdean/614f5566e6b428a4a14908b02483c1c1 to your computer and use it in GitHub Desktop.
Angular | Parallel API Requests
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @author Muhammad Faisal | |
* @description Service for getting data. | |
*/ | |
// Angular Imports | |
import { Injectable } from '@angular/core'; | |
import { HttpErrorResponse } from '@angular/common/http'; | |
import { forkJoin as observableForkJoin, Observable } from 'rxjs'; | |
@Injectable() | |
export class DataService { | |
/** | |
* Initializes an instance of DataService class. | |
*/ | |
constructor(private readonly _messageService: MessageService) { } | |
/** | |
* Gets the messages for given message ids. | |
* @param messageIds Message IDs. | |
*/ | |
public getMessages(messageIds: number[]): Observable<Message[]> { | |
return new Observable((observer) => { | |
// Create message request observables | |
const messageRequests: Observable<Message>[] = []; | |
for (const id of messageIds) { | |
messageRequests.push(this._messageService.getById(id)); | |
} | |
// Create a parallel request to get messages | |
const parallelRequests$ = observableForkJoin(messageRequests); | |
parallelRequests$.subscribe((result) => { | |
observer.next(result); | |
observer.complete(); | |
}, (error: HttpErrorResponse) => observer.error(error)); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment