如何在Angular 2中使用多个Http请求

Que*_*tin 5 javascript api typescript angular

我正在使用Angular 4和一个API创建一个简单的应用程序,它有多个页面用于他们的请求.

例如,我使用此URL获取10个第一个字符: http://swapi.co/api/people/

为了得到接下来的10个人,我必须向这个网址发出请求: http://swapi.co/api/people/?page=2

如何在一个请求中获得所有人?或者通过良好实践制定所有请求的解决方案是什么?

Mih*_*nut 13

您必须使用forkJoin方法才能从多个源加载数据.

首先,将它们包含在typescript文件中.

import {Observable} from 'rxjs/Rx';
Run Code Online (Sandbox Code Playgroud)

很多时候,我们需要从多个源加载数据,我们需要等到所有数据都加载完毕.

forkJoin方法包装多个Observables.换句话说,我们forkJoin用来运行concurrenthttp 请求.

subscribe()forkJoin在整个Observable集上设置处理程序的方法.

你可以在这里阅读更多关于forkJoin的内容 ,包括很多例子.

假设您必须获得前10页.

var pages:number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
Run Code Online (Sandbox Code Playgroud)

或者干脆: 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);
Run Code Online (Sandbox Code Playgroud)