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

问题描述

链接一系列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.

如果您的任务是三个相互独立的独立任务/可观察对象,则考虑使用forkJoin(所有可观察对象同时开始,并且最后一个可观察对象完成时它返回结果)

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 => {
   ...
});

这篇关于RxJ中依赖于链的可观察变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 15:52