Execute Multiple HTTP Requests in Angular
The problem
The solution
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]);
}
}Last updated
