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.
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()exportclassRestService { 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 dummylet 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());returnObservable.forkJoin([url1, url2]); }}
import {Component, OnInit} from'@angular/core';import {RestService} from"../rest.service";@Component({ selector:'app-demo', templateUrl:'./demo.component.html', styleUrls: ['./demo.component.css']})exportclassDemoComponentimplementsOnInit { dataFromRequest1:any; // data from url 1 dataFromRequest2:any; // data from url 2constructor(private restService:RestService) { }ngOnInit() {this.restService.getDataFromTwoResources().subscribe(responseList => {/* The response list is an array. In order to access data from each individual request, you need to use an index. */this.dataFromRequest1 = responseList[0];this.dataFromRequest2 = responseList[1]; }); }}
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.