如何在Angular 4中使用多个Http请求 [英] How to use multiple Http Requests in Angular 4

查看:153
本文介绍了如何在Angular 4中使用多个Http请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Angular 4& amp;创建一个简单的应用程序;一个有多个页面供其请求的API.

I'm making a simple app with Angular 4 & an API who has several pages for their requests.

例如,我使用此url获得前10个字符: http://swapi.co/api/people/

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

要获得接下来的10个人,我必须向该URL发出请求:http://swapi.co/api/people/?page=2

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 ?

推荐答案

您必须使用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);

这篇关于如何在Angular 4中使用多个Http请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆