import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [ BrowserModule, FormsModule, HttpClientModule ],
declarations: [ AppComponent, HelloComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
<p>
It hard to call http request in loop? Yes it is.!
</p>
<p>
We can resolve that issue using <strong>forkJoin</strong>. Let's Go
</p>
<h1> Please check console for http response. </h1>
<p>
<strong>forkJoin</strong> takes array argument of requests.
</p>
<p>
In example I tried to call 4 different country api as once and we will get output in one bulk array. That is in proper order which as request array we sent.!
</p>
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { forkJoin } from 'rxjs/observable/forkJoin';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
response = [];
constructor(public http: HttpClient) {
const request1 = this.http.get('https://restcountries.eu/rest/v1/name/india');
const request2 = this.http.get('https://restcountries.eu/rest/v1/name/us');
const request3 = this.http.get('https://restcountries.eu/rest/v1/name/ame');
const request4 = this.http.get('https://restcountries.eu/rest/v1/name/ja');
const requestArray = [];
requestArray.push(request1);
requestArray.push(request2);
requestArray.push(request3);
requestArray.push(request4);
forkJoin(requestArray).subscribe(results => {
console.log(results);
this.response = results;
});
}
}