angular - 使用 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()
则不应调用。这种场景的正确模式是什么?
解决方案
你可以像下面这样压缩代码
of(form.dirty).pipe(
switchMap(dirty=>dirty?myService.saveTheThing(form.value):of(true)),
switchMap(e=>myService.finalizeTheThing())
)
推荐阅读
- c++ - Opencv 从缓冲区写入和读取
- javascript - 用值初始化 Guard
- javascript - Chrome [VM] 文件在每次加载时创建事件处理程序
- python - 计算熊猫数据框中的摘要行
- php - mysqli_fetch_assoc() 在响应版本中不返回任何内容
- php - preg_replace 用于字符串中的“phpbb”报价和颜色标签
- nlp - 句子的实体检测在训练和测试句子中有所不同
- asp.net-mvc - 通过剃刀初始化打字稿变量值
- python-3.5 - 无法建立初始 TCP/IP 连接 (Chilkat-Python)
- notepad++ - 需要正则表达式来匹配记事本++中的特定模式