angular - 链接两个以上的 Angular Observable 调用

标签 angular rxjs

我目前正在开发 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

最佳答案

您可以使用mergeMapforkJoin,使用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}`));

Handling Observables that depend on each other

关于angular - 链接两个以上的 Angular Observable 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50591287/

相关文章:

javascript - Angular 4 : Load data from Json

angular - 如何在下拉列表中将标签设置为空字符串?

javascript - Angular2错误: Return type of public method from exported class has or is using private name

typescript - Rxjs 将 API 结果 Observable 转换为服务函数中的另一个 Observable

angular - Angular 4 中 Observable 和 Promise 的简单定义

angular - typescript 错误 : Type Observable<Object> is not assignable to type

javascript - 无法从 Angular 9 中的服务加载变量

javascript - 为什么 Observable.create() 中的 setInterval() 一直在运行?

javascript - RxJs 映射后未定义的值

Angular2 可观察定时器条件