如何在Angular2中链接Http调用? [英] How to chain Http calls in Angular2?

查看:64
本文介绍了如何在Angular2中链接Http调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Angular2和Http Observable的新手.我有一个调用Http服务并返回Observable的组件.比我更喜欢该Observable,它可以正常工作.

I'm new to Angular2 and Http Observable. I have a component which calls Http service and returns Observable. Than I subscribe to that Observable and it works fine.

现在,我想要在该组件中,调用第一个Http服务后,如果调用成功,则调用其他Http服务并返回该Observable.因此,如果第一次调用未成功,则组件将返回该Observable,相反,它将返回第二次调用的Observable.

Now, I want,in that component, after calling first Http service,if call is success, call other Http service and return that Observable. So, if first call is not success the component returns that Observable, opposite it returns Observable of second call.

所以,问题是,链接Http调用的最佳方法是什么?有没有什么优雅的方法,例如单子?

So, question is, what is the best way to chain Http calls? Is there any elegant way, for example like monads?

推荐答案

您可以使用mergeMap运算符来完成此操作.

You can do this using the mergeMap operator.

Angular 4.3+(使用HttpClientModule)和RxJS 6 +

Angular 4.3+ (using HttpClientModule) and RxJS 6+

import { mergeMap } from 'rxjs/operators';

this.http.get('./customer.json').pipe(
  mergeMap(customer => this.http.get(customer.contractUrl))
).subscribe(res => this.contract = res);

角度< 4.3(使用HttpModule)和RxJS< 5.5

Angular < 4.3 (using HttpModule) and RxJS < 5.5

导入运算符mapmergeMap,然后可以按如下所示链接两个调用:

Import the operators map and mergeMap, then you can chain two calls as follows:

import 'rxjs/add/operator/map'; 
import 'rxjs/add/operator/mergeMap';

this.http.get('./customer.json')
  .map((res: Response) => res.json())
  .mergeMap(customer => this.http.get(customer.contractUrl))
  .map((res: Response) => res.json())
  .subscribe(res => this.contract = res);

此处有更多详细信息: http://www.syntaxsuccess.com/viewarticle/angular-2.0-and-http

Some more details here: http://www.syntaxsuccess.com/viewarticle/angular-2.0-and-http

可以在此处

这篇关于如何在Angular2中链接Http调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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