首页 > 解决方案 > 使用 RXJS 有条件地向管道添加操作

问题描述

我需要有条件地在另一个 API 调用之前进行 API 调用。场景是我有一个表单和两个按钮,保存和完成。当我按下 finalize 时,如果表单值已更改,则需要先保存它。这是我当前的解决方案,但这并不是我真正想要的(我不想要一个数组,我只想要最后一个):

const operations$ = [];

if (form.dirty) {
  operations$.push(myService.saveTheThing(form.value).pipe(...))
}

operations$.push(myService.finalizeTheThing().pipe(...));

combineLatest(operations$).subscribe(() -> { ... });

我并不真正关心订阅块中的保存操作结果,我宁愿只接收返回的一个值finalizeTheThing()而不是返回的数组combineLatest。这是我尝试过的另一件事,类似于我想要的,但显然它不是这样工作的:

const stream$ = of(null);

if (form.dirty) {
  stream$.pipe(
    switchMap(() => myService.saveTheThing(form.value).pipe(...))
  );
}

stream$.pipe(
  switchMap(() => myService.finalizeTheThing()
);

stream$.subscribe(myThing => { ... })

当然,如果saveTheThing()失败,finalizeTheThing()则不应调用。这种场景的正确模式是什么?

标签: angularrxjsrxjs6

解决方案


你可以像下面这样压缩代码

of(form.dirty).pipe(
   switchMap(dirty=>dirty?myService.saveTheThing(form.value):of(true)),
   switchMap(e=>myService.finalizeTheThing())
)

推荐阅读