且构网

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

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

更新时间:2021-08-01 05:46:21

您必须使用 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 requests.

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