通过forkJoin并行HTTP请求和响应识别 [英] Parallel http requests via forkJoin and response identification

查看:137
本文介绍了通过forkJoin并行HTTP请求和响应识别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对端点进行并行的独立调用.

I would like to make parallel independent calls to an endpoint.

首先,我构造呼叫,然后呼叫 forkJoin .

First I construct my calls then I call forkJoin.

getAllDirections(data: Object, date: string) {
  let urls = [];
  for (let elm in data) {
    let url = `http:XXXXX?date=${date}&directions=${data[elm].All.join()}`;
    urls.push(this.http.get<ISchedules>(url));
  }
  return forkJoin(urls).pipe(
    map(dirData => {
      let dataSorted = dirData.map(elm => _.groupBy(elm.data, 'direction'));
      return dataSorted;
    })
  );
}

数据参数是我传递给URl的参数对象

the data params is an objects of params that I pass to the URl

data = {
    b1: [params1],
    b2: [params2],
    b3: [params3]
}

作为结果,我将能够构造该对象

What I would as result be able to construct this object

dataRes = {
    b1: [resDataofParams1],
    b2: [resDataofParams2],
    b3: [resDataofParams3]
}

当我获得数组响应时,我应该影响每个数组项,使其对应的 b {n} ,如何以与 forkJoin中传递的顺序相同的顺序获取响应代码>?还是有一种方法可以在 this.http.get< ISchedules>(url)中传递参数,并在我得到数据响应时将其获取?

When I get the array response I should affect every array item to it's corresponding b{n}, How can I get the responses in the same order that I passed in forkJoin ? Or it there a way to pass a parameter in this.http.get<ISchedules>(url) and get it when I get data response ?

推荐答案

在我看来,最好使用已经创建的方法在RXJS 6.5中,您需要传递一系列可观察对象:

In my view, it is better to use already created method forkJoin() from library RXJS. In RXJS 6.5 you need to pass an array of observables:

const combined = Observable.forkJoin(
  [(this.http.get('https://foourl1').map((res: Response) => res.json()),
  of(this.http.get('https://foourl1').map((res: Response) => res.json())]
)

combined.subscribe(latestValues => {
    const [ data_changes , data_all ] = latestValues;
    console.log( "data_changes" , data_changes);
    console.log( "data_all" , data_all);
});

forkJoin 将在所有调用完成后返回数据并返回结果.

forkJoin will return data when all calls are finished and return result.

另一个例子:

const request1 = this.http.get('https://restcountries.eu/rest/v1/name/india');
const request2 = this.http.get('https://restcountries.eu/rest/v1/name/us');
const request3 = this.http.get('https://restcountries.eu/rest/v1/name/ame');
const request4 = this.http.get('https://restcountries.eu/rest/v1/name/ja');

const requestArray = [];
requestArray.push(request1);
requestArray.push(request2);
requestArray.push(request3);
requestArray.push(request4);

forkJoin(requestArray).subscribe(results => {
  console.log(results);
  this.response = results;
});

所有结果按顺序排序,然后将项目推送到 requestArray.中可以在

All results are ordered accordingly pushed items into requestArray. It can be seen in a stackblitz example.

这篇关于通过forkJoin并行HTTP请求和响应识别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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