Reputation: 711
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 ?
Upvotes: 5
Views: 7046
Reputation: 48337
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);
Upvotes: 14