RxJS - 链接多个可观察对象并在其间做其他事情

Viq*_*qas 1 rxjs angular

我在网上查了很多资料,但找不到任何可以描述我的问题的内容。

我目前正在使用 Angular 5。

基本上,我想执行一个puthttp请求,然后一旦完成就做一些事情,然后执行另一个gethttp请求并做更多的事情。

这是我使用嵌套订阅的代码(我知道你不应该这样做):

this.projectService.updateProject(this.project).subscribe(
  subscribe => {
    doSomethingAfterTheUpdate();
    this.projectService.get(this.id).subscribe(
      subscribe => {
        doSomethingAfterTheGet();
        });
    });
Run Code Online (Sandbox Code Playgroud)

如您所见,我正在更新项目,然后获取项目。我怎样才能使用 RxJS 正确地做到这一点。我研究了 Concat 和 MergeMap 方法,但我想在更新和获取之后执行一些操作。

Ale*_*sky 5

您应该能够使用操作符tapswitchMap来实现此目的:

import { switchMap, tap } from 'rxjs/operators';

// ...

this.projectService.updateProject(this.project)
  .pipe(
    tap(() => doSomethingAfterTheUpdate()),
    switchMap(() => this.projectService.get(this.id)),
    tap(() => doSomethingAfterTheGet())
  )
  .subscribe(results => console.log(results));
Run Code Online (Sandbox Code Playgroud)

希望这有帮助!