如何在Angular2中链接Http调用 [英] How to chain Http calls in Angular2
问题描述
我是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的最佳方法是什么电话?是否有任何优雅的方式,例如monad?
So, question is, what is the best way to chain Http calls? Is there any elegant way, for example like monads?
推荐答案
你可以使用 mergeMap
运算符
首先按如下方式导入运算符:
First import the operator as follows:
import'rxjs / add / operator / mergeMap';
然后,这里是你如何链接两个电话:
Then here is how you chain two calls:
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
有关mergeMap运算符的更多信息,请访问此处
More information about the mergeMap operator can be found here
这篇关于如何在Angular2中链接Http调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!