我可以找到大量链接两个调用的示例,但我有 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/