我目前正在开发 Angular 5 服务,需要链接四个单独的 Observable 调用,每个后续调用都使用部分或所有先前调用中的数据。我见过一些组合两个调用的示例,但我不知道如何使用两个以上的调用(并尝试通过 flatMap
扩展它们,导致先前调用的数据在后续调用中不可用) .
-
CallOne
返回Observable<Foo[]>
- 然后我需要进行一些过滤来选择特定的
Foo
- 然后我需要进行一些过滤来选择特定的
-
CallTwo
需要Foo
并返回Observable<FooTwo[]>
- 然后我需要进行一些过滤来选择特定的
FooTwo
- 然后我需要进行一些过滤来选择特定的
-
CallThree
需要FooTwo
并返回Observable<FooThree[]>
- 然后我需要进行一些过滤来选择特定的
FooThree
- 然后我需要进行一些过滤来选择特定的
-
CallFour
需要Foo
,一个FooTwo
,以及FooThree
并返回Observable<Bar[]>
之后,我需要访问所选的 Foo
, FooTwo
, FooThree
和一个特定的Bar
。
最佳答案
您可以使用mergeMap
和forkJoin
,使用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
})
但是,如果您想让它同步并使请求依赖于先前的调用,您可以这样做,
const request1$ = Rx.Observable.of('response1').delay(2000);
const request2$ = Rx.Observable.of('response2').delay(100);
Rx.Observable.forkJoin(request1$, request2$)
.subscribe(res => console.log(`forkJoin: ${res}`));
关于angular - 链接两个以上的 Angular Observable 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50591287/