Ionic2 中的多个 $http 请求

mah*_*ail 2 http request typescript ionic2 angular

我想知道多个请求是否:

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

例如:调用$http request 1then $http request 2

seb*_*ras 5

据我了解,您正在尝试发出多个 http 请求,然后在所有这些请求结束后处理响应。例如,您可能需要从多个源加载数据,并延迟加载后逻辑,直到所有数据都加载完毕。

如果是这种情况,您可以使用 ReactiveX Observables,因为它提供了一种称为forkJoin()包装多个 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())
    );
  }

}
Run Code Online (Sandbox Code Playgroud)

然后你可以通过订阅那个 observable 来获取所有数据:

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