【问题标题】:Angular 2 combine three http calls with flatMap? RxJs?Angular 2 将三个 http 调用与 flatMap 结合起来? RxJs?
【发布时间】:2017-11-25 16:31:58
【问题描述】:

我可以找到很多链接两个调用的示例,但我有 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 操作返回一个 observable。

谁能指出我正确的方向?

非常感谢它,因为它让我发疯!

谢谢 保罗

【问题讨论】:

  • 你是否将结果绑定到类型为Observable的变量?
  • 你能复制粘贴你的完整代码吗?
  • nvm,发现问题

标签: angular http rxjs


【解决方案1】:

您可以根据需要多次使用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 运算符。我们不再将一些运算符原型化为Observables,而是导入它们并按如下方式使用它们:

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
    });

【讨论】:

  • @BrahimLAMJAGUAR 谢谢,但我更新了我的答案。有实现相同目标的新方法。看看吧!
【解决方案2】:

flatMap() 期望 Observable 作为返回值,但您返回 Subscription

像这样修复它:

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

补充说明:

这些请求仍然会依次执行,而不是并行执行。如果你想加快速度,你可以使用Observable.forkJoin():

Observable.forkJoin(
    call1(params),
    call2(params),
    call3(params)
).subscribe((responses) => {
    // responses[0] -> response of call1
    // responses[1] -> response of call2
    // responses[2] -> response of call3
})

【讨论】:

  • 谢谢,太棒了。在这种情况下,我不能使用 forkJoin,因为调用都是相互依赖的......
猜你喜欢
  • 1970-01-01
  • 2021-09-28
  • 2017-08-21
  • 2021-08-21
  • 2020-04-19
  • 1970-01-01
  • 1970-01-01
  • 2019-12-25
  • 1970-01-01
相关资源
最近更新 更多