Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use multiple Http Requests in Angular 4

I'm making a simple app with Angular 4 & an API who has several pages for their requests.

For example I get the 10 first characters with this url : http://swapi.co/api/people/

And to get the next 10 people I have to make request to this url : http://swapi.co/api/people/?page=2

How can I get all people in one request ? Or what is the solution to make all requests with good practices ?

like image 618
Nitneq Avatar asked Jul 15 '17 10:07

Nitneq


People also ask

Why we use forkJoin in Angular?

Why use forkJoin ? This operator is best used when you have a group of observables and only care about the final emitted value of each. One common use case for this is if you wish to issue multiple requests on page load (or some other event) and only want to take action when a response has been received for all.

How do I stop multiple API calls?

On clicking on tabs you interchange state and you use ngOnInit() method every time when a state is changed to get the data.In this way, you can reduce API calls by using nested routing.

What is HTTP request in angular?

HttpRequest represents an outgoing request, including URL, method, headers, body, and other request configuration options. Instances should be assumed to be immutable. To modify a HttpRequest , the clone method should be used.


1 Answers

You have to use forkJoin method in order to load data from more than one source.

First of all, include them in the typescript file.

import {Observable} from 'rxjs/Rx';

UPDATE

For new versions of Angular use this:

import { forkJoin } from 'rxjs';

Many times, we need to load data from more than one source, and we need to wait until all the data has loaded.

forkJoin method wraps multiple Observables. In the other words, we use forkJoin to run concurrent http requests.

subscribe() method of forkJoin sets the handlers on the entire set of Observables.

You can read more about forkJoin here, including a lot of examples.

Suppose you have to get first 10 pages.

var pages:number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

Or simply: var pages:number[] = new Array(10).fill().map((v, i) => i + 1);

// map them into a array of observables and forkJoin
return Observable.forkJoin(
   pages.map(
      i => this.http.get('http://swapi.co/api/people/?page=' + i)
        .map(res => res.json())
   )
).subscribe(people => this.people = people);
like image 110
Mihai Alexandru-Ionut Avatar answered Sep 17 '22 09:09

Mihai Alexandru-Ionut