以角度2进行并行呼叫http get或post呼叫 [英] Make parallel calls http get or post calls in angular 2

查看:87
本文介绍了以角度2进行并行呼叫http get或post呼叫的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在角度2中进行并行调用HTTP获取或发布调用?

How to make parallel calls HTTP get or post calls in angular 2?

我对一个愈伤组织的响应有2个服务呼叫,必须打另一个电话.
有人可以建议我如何使用错误处理方案进行这些并行调用吗?

I have 2 service calls on the response of one callus have to make another call.
Could some suggest me how to call make these parallel calls with error handling scenarios?

推荐答案

如果您的服务基于Observable而不是Promise,则可以执行forkJoin.它并行运行所有可观察的序列.

If your service is Observable based instead of Promise you can do forkJoin. It runs all observable sequences in parallel.

对于RxJS版本< 6

For RxJS version < 6

import 'rxjs/add/observable/forkJoin';

确保从rxjs库中获取import forkJoin

Observable.forkJoin(myService.getCall(),
            myService.postCall(),
            ...)
            .subscribe((res) => {
              res[0] // this is first service call response,
              res[1] // this is second service call response
              ...
});

或者,如果您希望它是顺序的,请先执行第一个电话,然后在完整的电话上进行第二个电话.

Or if you want it to be sequential do the first call and on complete call second.

myService.getCall().subscribe((response) => {
  // handle response
}, (error) => {
  // handle error here
}, () => {
  // this is complete block and it is triggered when obervable is complete
  myService.postCall();
}

编辑:RxJS 6及更高版本的forkJoin已更改

for RxJS 6 and above forkJoin has changed

服务:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { forkJoin, Observable } from 'rxjs';

@Injectable()
export class MyService {

  constructor(private  http: HttpClient) {
  }

  getAndPost(): Observable<any> {
    return forkJoin(
      this.http.get('/api/get'),
      this.http.post('/api/post')
    );
  }
}

组件:

firstResponse: any;
secondResponse: any;

constructor(private myService: MyService) {
}

myFunction(): void {
  this.myService.getAndPost().subscribe((res) => {
    this.firstResponse = res[0],
    this.secondResponse = res[1]
  });
}

这篇关于以角度2进行并行呼叫http get或post呼叫的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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