Angular 6 and RxJS: Multiple API Calls Simultaneously

Angular 6 and RxJS are fantastic tools for developing single page web applications. In Angular 6, a problem we often face, is multiple components require some set of shared data. Sure, we could copy and paste the individual service calls, but that’s not the best approach. We should really be trying to centralize shared data requests.

First, we need to make a wrapper object to encapsulate the requested data:

export interface IDataCollection {
    data?: IApiResponse<Data[]>;
    secondData?: IApiResponse<SecondData[]>;
}

The next thing to do is make the request function:

/** Static for example simplicity **/
export class DataCollectionService {
    public static getDataCollection(dataService: DataService): Observable<IDataCollection> {
        return Observable.forkJoin(
            dataService.getData(),
            dataService.getSecondData(),
        ).map(response => {
                let dataCollection = {
                    data: response[0],
                    secondData: response[1]
                 } as IDataCollection;
                 // More logic goes here.

                 return dataCollection;
            }
        );
    }
}

Now, all you need to do is subscribe to the observable:

DataCollectionService.getDropdownCollection(this.dataService).subscribe(
            (dataCollection: IDataCollection) => {
                this.data = dataCollection.data;
                this.secondData = dataCollection.secondData;
                // More logic goes here.

            },
            // Should be global error handler in your app.
            (err: any) => console.log(err),
            // Should be your logging framework here
            () => "Retrieved data for dropdown boxes."
);

That’s it! You’ve combined multiple service calls into one concise function.

Let me know if this worked for you.

Leave a Reply

Your email address will not be published.