如何使用RxJS在Angular 6中创建一系列HTTP请求 [英] How to make a sequence of http requests in Angular 6 using RxJS

查看:116
本文介绍了如何使用RxJS在Angular 6中创建一系列HTTP请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在网上寻找解决方案,但找不到适合我的用户情况的任何解决方案.我正在使用MEAN堆栈(角度6),并且有注册表.我正在寻找一种执行对API的多个HTTP调用的方法,每个调用都依赖于前一个返回的结果.我需要这样的东西:

I've been looking for a solution all over the web, but couldn't find anything that fits my user case. I'm using the MEAN stack (Angular 6) and I have a registration form. I'm looking for a way to execute multiple HTTP calls to the API and each one is dependent on the returned result from the previous one. I need something that looks like this:

firstPOSTCallToAPI('url', data).pipe(
    result1 => secondPOSTCallToAPI('url', result1)
    result2 => thirdPOSTCallToAPI('url', result2)
    result3 => fourthPOSTCallToAPI('url', result3)
    ....
).subscribe(
    success => { /* display success msg */ },
    errorData => { /* display error msg */ }
);

我需要使用哪种RxJS运算符组合来实现此目的?一种可能的解决方案是嵌套多个订阅,但是我想避免这种情况,并使用RxJS更好地实现.还需要考虑错误处理.

What combination of RxJS operators do I need to use to achieve this? One possible solution would be to nest multiple subscriptions, but I want to avoid that and do it better with RxJS. Also need to think about error handling.

推荐答案

对于取决于先前结果的调用,您应该使用concatMap

For calls that depend on previous result you should use concatMap

firstPOSTCallToAPI('url', data).pipe(
    concatMap(result1 => secondPOSTCallToAPI('url', result1))
      concatMap( result2 => thirdPOSTCallToAPI('url', result2))
       concatMap(result3 => fourthPOSTCallToAPI('url', result3))
    ....
).subscribe(
    success => { /* display success msg */ },
    errorData => { /* display error msg */ }
);

如果您的异步方法不取决于先前的异步调用的返回值,则可以使用

if your async method does not depend on return value of the precedent async call you can use

   concat(method(),method2(),method3()).subscribe(console.log)

这篇关于如何使用RxJS在Angular 6中创建一系列HTTP请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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