问题描述
我可以找到很多链接两个调用的示例,但我有 3 个 http 调用使用前一个调用中的数据一个接一个地进行.
I can find plenty of examples with chaining two calls but i have 3 http calls to make one after another using data from the previous call.
我有两个使用 flatMap 工作
I have two working using flatMap
所以:
call1(params)
.flatMap((res1)=> {
return call2(params)
.subscribe(r=>r...)
但是对于三个调用,我正在尝试同样的事情,但我认为您不能将 flatMap 链接在一起?
But for three calls i am trying the same thing but i don't think you can chain flatMaps together?
call1(params)
.flatMap((res1)=> {
return call2(params)
.flatMap((res2)=> {
return call3(params)
.subscribe(r=>r...)
我收到一条错误消息,指出订阅不可分配到类型观察输入.每个 call1 都从 http 操作返回一个可观察对象.
I get an error saying subscription is not assignable to type observation input. Each of those call1 returns an observable from an http operation.
谁能指出我正确的方向?
Can anyone point me in the right direction?
真的很感激,因为它让我发疯了!
Would really appreciate it as it's driving me nuts!
谢谢保罗
推荐答案
您可以根据需要多次使用 flatMap
.但是,您每次都必须返回一个 Observable.例如
You can use flatMap
as many times as you want. However, you have to return an Observable each time.E.g.
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
,而是导入它们并按如下方式使用它们:
Starting from RxJs v5.5, there came Pipeable
operators. We, no longer, prototype some operators to Observable
s, instead we import them and use them as follows:
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 结合起来?RxJs?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!