问题描述
我可以找到很多链接两个电话的例子,但我有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...)
但对于三个电话,我正在尝试同样的事情,但我不认为你可以将flatMaps连在一起吗?
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操作返回一个observable。
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?
真的很感激它s让我疯了!
Would really appreciate it as it's driving me nuts!
谢谢
Paul
thanksPaul
推荐答案
您可以根据需要多次使用 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
s,而是导入它们并按如下方式使用它们:
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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!