How to use multiple Http requests in Angular 2

I am making a simple application with Angular 4 and an API that has several pages for their requests.

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

And in order to get the following 10 people, I have to make a request to this URL: http://swapi.co/api/people/?page=2

How can I get all people on one request? Or what is the solution for all queries with best practices?

+4
source share
1 answer

You need to use the method forkJointo load data from multiple sources.

First of all, include them in the file typescript.

import {Observable} from 'rxjs/Rx';

, , .

forkJoin Observables. , forkJoin concurrent http .

subscribe() forkJoin Observables.

forkJoin , .

, 10 .

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

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

// map them into a array of observables and forkJoin
Observable.forkJoin(
   pages.map(
      i => this.http.get('http://swapi.co/api/people/?page=' + i)
        .map(res => res.json())
   )
).subscribe(people => this.people = people);
+11

Source: https://habr.com/ru/post/1681508/


All Articles