且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2021-08-01 05:45:57

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

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

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

First of all, include them in the typescript file.

import {Observable} from 'rxjs/Rx';

更新

对于新版本的Angular,请使用以下代码:

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方法包装多个Observables.换句话说,我们使用forkJoin来运行concurrent http 请求.

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

subscribe()方法在整个 Observables 集合上设置处理程序.

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

您可以详细了解 forkJoin 此处,包括许多示例.

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

假设您必须获得前10页.

Suppose you have to get first 10 pages.

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