如何避免使用 rxjs 进行嵌套订阅?

How can avoid nested subscribes with rxjs?

我有 rxjs 嵌套 observables,工作正常。

this.service.save(body).subscribe(
   () => {
       this.dialog.confirmDialog({
           title: '',
           message: 'Save okay',
           caption: 'OK'
       })
       .subscribe((yes) => {
            this.service.getGoal().subscribe(
             result => {
                 this.loading(result);
                }
              );
          });
       }
     });

这段代码做了三件事。先保存对象,再弹出确认window。最后调用服务刷新页面。 我在这里使用嵌套订阅。我知道这在理论上并不好,我应该用 rxjs 的一些映射函数替换它们。但我就是不知道怎么办?感谢您提供代码。

这在没有嵌套订阅的情况下应该大致相同:

this.service.save(body).pipe(
  mergeMap(_ => this.dialog.confirmDialog({
    title: '',
    message: 'Save okay',
    caption: 'OK'
  })),
  mergeMap(yes => this.service.getGoal())
).subscribe(result =>
  this.loading(result)
);

您应该使用 RxJs 运算符来使您的可观察流更干净。根据您的用例,一些常见的运算符包括 mergeMapswitchMapmap、e.t.c.

嵌套订阅会导致内存泄漏等问题。