sarnei
sarnei

Reputation: 277

Multi calls using 'HttpClient' Angular 8

I would like to do a multi call using 'HttpClient'. Something similar that I used to use with axios.

Using axios with Vue:

return axios.all([
      axios.get('/friends/name'),
      axios.get('/family/name'),
      axios.get('/collegue/name'),
])

Trying with angular:

return this.http.all([
      this.http.get('/friends/name'),
      this.http.get('/family/name'),
      this.http.get('/collegue/name'),
])

error TS2339: Property 'all' does not exist on type 'HttpClient'

Upvotes: 0

Views: 84

Answers (3)

Adrita Sharma
Adrita Sharma

Reputation: 22203

Try with forkJoin like this:

 ngOnInit() {    
    const request1 = this.http.get('/friends/name');
    const request2 = this.http.get('/family/name');
    const request3 = this.http.get('/collegue/name');

    forkJoin([request1, request2, request3]).subscribe(data => {
      this.response1 = data[0];
      this.response2 = data[1];
      this.response3 = data[2];
    });
  }

Upvotes: 1

Celsiuss
Celsiuss

Reputation: 905

When making a request using the HttpClient, it will return an rxjs Observable which you will have to subscribe to in order for it to make the request. You should look into one of these operators from rxjs, depending on your use case.

You could for example use the merge operator like this:

const requests = merge(
    this.http.get('/friends/name'),
    this.http.get('/family/name'),
    this.http.get('/collegue/name')
);
requests.subscribe(console.log); // Executes the requests and logs them as they complete

Upvotes: 1

Aravind
Aravind

Reputation: 41581

You have to use a forkJoin operator and subscribe to the data as below

forkJoin([
  this.http.get('/friends/name'),
  this.http.get('/family/name'),
  this.http.get('/collegue/name'),
 ])

Upvotes: 1

Related Questions