如何在 Angular 2 中链接 HTTP 调用? [英] How can I chain HTTP calls in Angular 2?

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

问题描述

我是 Angular 2 和 HTTP Observables 的新手.我有一个调用 HTTP 服务并返回一个 Observable 的组件.然后我订阅了那个 Observable,它工作正常.

I'm new to Angular 2 and HTTP Observables. I have a component which calls an HTTP service and returns an Observable. Then I subscribe to that Observable and it works fine.

现在,我想在那个组件中,在调用第一个 HTTP 服务之后,如果调用成功,调用另一个 HTTP 服务并返回那个 Observable.所以,如果第一次调用不成功,组件返回那个 Observable,相反它返回第二次调用的 Observable.

Now, I want, in that component, after calling the first HTTP service, if the call was successful, to call another HTTP service and return that Observable. So, if the first call is not successful the component returns that Observable, opposite it returns Observable of the second call.

链接 HTTP 调用的最佳方式是什么?有没有一种优雅的方式,例如 monads?

What is the best way to chain HTTP calls? Is there an 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

可以在此处

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

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