本文介绍了在 RxJs 中链接依赖的 Observable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

链接一系列 HttpClient 调用的最佳实践"是什么(假设当前调用取决于先前调用的结果)?以下解决方案是有效的,但显然不推荐.每个 get 返回一个 Observable.使用解决方案中首选的管道"运算符(RxJs 中较新的方法).

What is "best practices" for chaining a sequence of HttpClient calls (assume the current call depends on the results of the previous calls)? The following solution is functional but apparently not recommended. Each get returns an Observable. Use of the "pipe" operator preferred in solution (the newer approach in RxJs).

ngOnInit() {
  this.firstService.get().subscribe((first) => {
    this.secondService.get().subscribe(second => {
      this.thirdService.get().subscribe(third => {
        ... possibly more nested calls ...
      })
    })
  })
}

推荐答案

您的代码远远超出了最佳实践.永远不要在另一个内部订阅.

Your code is far beyond best practice. Never do subscription inside another.

如果你的任务是三个不相互依赖的独立任务/observable,那么考虑使用forkJoin(所有的Observable同时开始,当最后一个Observable完成时返回结果)

If your tasks are three seperate tasks/observables which do not depends each other, then consider to use forkJoin (all Observables start at the same time and when the last observable finishes It returns result)

let observable1(param1);
let observable2(param2);
let observable3(param3);

let joinedObservables = forkJoin(observable1, observable2, observable3).subscribe(x => {
  let result1 = x[0];
  let result2 = x[1];
  let result3 = x[2];

  ...
});

如果它们的结果相互依赖,你可以使用 switchMapflatMapmergeMapexhaustMap(检查差异)

If their results depends on each other you can use switchMap, flatMap, mergeMap, exhaustMap (check differences)

let resultObservable =  return this.observable1().pipe(mergeMap((param1) => {
  return this.observable2().pipe(map((param1) => {

    ....        

    return <result>;
  }));
}));

resultObservable.subscribe(x => {
   ...
});

这篇关于在 RxJs 中链接依赖的 Observable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 01:49