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

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

问题描述

我正在使用 Angular 4 & 制作一个简单的应用程序一个 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 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);

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

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