如何使用 RxJS 在 Angular 6 中发出一系列 http 请求
我一直在网上寻找解决方案,但找不到适合我的用户案例的任何解决方案.我正在使用 MEAN 堆栈(Angular 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)