Angular 2 将三个 http 调用与 flatMap 结合起来?接收者?

标签 angular http rxjs

我可以找到大量链接两个调用的示例,但我有 3 个 http 调用使用前一个调用的数据一个接一个地进行。

我有两个人在使用 flatMap

所以:

call1(params)
  .flatMap((res1)=> {
     return call2(params)
        .subscribe(r=>r...)

但是对于三个调用,我正在尝试同样的事情,但我不认为你可以将 flatMaps 链接在一起?

call1(params)
  .flatMap((res1)=> {
     return call2(params)
        .flatMap((res2)=> {
            return call3(params)
               .subscribe(r=>r...)

我收到一条错误消息,指出订阅不可分配给类型观察输入。这些 call1 中的每一个都从 http 操作返回一个可观察对象。

谁能指出我正确的方向?

真的很感激,因为它让我抓狂!

谢谢 保罗

最佳答案

您可以根据需要多次使用flatMap。但是,您每次都必须返回一个 Observable。 例如

myFunc() // returns an Observable of type X
        .flatMap((res: X) => {
           // returns an Observable of type Y
        })
        .flatMap((res: Y) => {
           // returns an Observable of type Z
        })
        .flatMap((res: Z) => {
           // returns an Observable of type Q
        })
        .subscribe((res: Q) => {
           // some logic
        });

RxJs 已更改

从 RxJs v5.5 开始,出现了 Pipeable 运算符。我们不再将一些运算符原型(prototype)化为 Observable,而是导入它们并按如下方式使用它们:

import { flatMap } from 'rxjs/operators';

myFunc() // returns an Observable of type X
    .pipe(
        flatMap((res: X) => {
           // returns an Observable of type Y
        }),
        flatMap((res: Y) => {
           // returns an Observable of type Z
        }),
        flatMap((res: Z) => {
           // returns an Observable of type Q
        })
    ).subscribe((res: Q) => {
       // some logic
    });

关于Angular 2 将三个 http 调用与 flatMap 结合起来?接收者?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44698649/

相关文章:

angular - 如何在 Angular5 的 ng2-select 中列出客户端?

angular - 点击事件坐标

android - 使 WCF 服务与 Android 兼容

java - 在 Java 7 中通过 HTTP 检索 XML

javascript - Observables 中的 Promise.all 等价物是什么?

Angular 2 模板使用 console.log

Angular 开发和 TFS

android - 由 ionic 框架制作的安全 android 应用程序

angular - 订阅可观察对象的主体

javascript - 如何去抖动内部组件的@Output?