繁体   English   中英

Angular 2将三个http调用与flatMap相结合? RxJs?

[英]Angular 2 combine three http calls with flatMap? 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操作返回一个observable。

谁能指出我正确的方向?

真的很感激它,因为它让我疯了!

谢谢保罗

您可以根据需要多次使用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运营商。 我们不再将一些运算符原型化为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
    });

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM