Execute Multiple HTTP Requests in Angular

The problem

There are times when you need to get multiple resources from the backend before you can render a view to the user. AJAX calls are asynchronous by nature, so you need to make sure that every request is finished before you move on.angular_multiple_httparrow-up-right

Execute multiple HTTP requests in Angular

The solution

Luckily for us, there is an elegant way to execute multiple HTTP requests in Angular 2/4 and wait for all of them to complete. Let’s write a code sample for this scenario. All we need is two classes. A REST service where we encapsulate HTTP request methods and a component that needs to use the backend data.

import {Injectable} from '@angular/core';
import {Http} from "@angular/http";
import {Observable} from "rxjs/Observable";
import 'rxjs/add/observable/forkJoin';

@Injectable()
export class RestService { 
constructor(private http: Http) { } 
/** 
* Sends two http GET requests to a backend and waits for all of them to finish. In this example,
* there are only two parallel HTTP requests, but you can use as many as you need 
* @returns {Observable<any[]>} 
*/ 
getDataFromTwoResources() {
        // The URLs in this example are dummy
        let url1 = this.http.get('localhost:8080/url-1').map(res => res.json());
        let url2 = this.http.get('localhost:8080/url-2').map(res => res.json());
        return Observable.forkJoin([url1, url2]);
    }
}

Note: This technique can be used for gathering requests from multiple servers or from the same server. All you need to know are the URLs for the resources.

Last updated