简体   繁体   中英

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 ?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM