Ionic2中有多个$ http请求 [英] Multiple $http requests in Ionic2

查看:155
本文介绍了Ionic2中有多个$ http请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道多个请求:

如果我的 $ http请求1 开始,让我们说 $ http request 1 结束并尝试拨打 $ http request 2 我的问题如何创建多个请求?

if my $http request 1 start , let's say $http request 1 ends and tried to call $http request 2. my question how can i create a multiple request ?

例如:call $ http request 1 然后 $ http请求2

for example : call $http request 1 then $http request 2.

推荐答案

据我所知,您尝试生成多个http请求,然后在所有请求结束时处理响应。例如,您可能需要从多个源加载数据,并延迟后加载逻辑,直到所有数据都已加载。

As I understand, you're trying to make more than one http request and then process the response when all those request have ended. For instance, you may need to load data from more than one source, and delay the post-loading logic until all the data has loaded.

如果是这种情况,可以使用ReactiveX Observables,因为它提供了一个名为 forkJoin()的方法来包装多个Observables。

If that's the case, you could use ReactiveX Observables because it provides a method called forkJoin() to wrap multiple Observables.

import {Injectable} from '@angular/core';
import {Http, Response} from '@angular/http';
import {Observable} from 'rxjs/Rx';

@Injectable()
export class MultipleHttpService {

  constructor(private http:Http) { }

  // If any single request fails, the entire operation will result in an error state.
  getData0AndData1() {
    return Observable.forkJoin(
      this.http.get('/app/data0.json').map((res:Response) => res.json()),
      this.http.get('/app/data1.json').map((res:Response) => res.json())
    );
  }

}

然后你就可以获得所有数据通过订阅该observable:

Then you could get all the data by subscribing to that observable:

// Code in your page ...
this.myMultipleHttpService.getData0AndData1()
    .subscribe(
      data => {
        this.data0= data[0]
        this.data1 = data[1]
      },
      err => console.error(err)
    );

这篇关于Ionic2中有多个$ http请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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