You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 7中如何在concatMap/switchMap内实现条件判断逻辑

问题根因

  • concatMap 要求回调必须返回 Observable 类型,你当前代码中printEmptyAlert()是普通方法调用无 Observable 返回值,导致流执行抛出类型错误。
  • 无文件名分支执行弹窗后,不需要执行后续下载逻辑,当前写法没有终止流,会导致订阅回调中处理Blob的代码接收到非预期值报错。

修复方案

  1. 先从rxjs导入空Observable对象EMPTY,用于无文件名分支终止流。
  2. 修改concatMap分支逻辑:无文件名时先执行弹窗,再返回EMPTY,直接结束流不会触发订阅的next回调。

修复后完整代码

import { EMPTY } from 'rxjs';

// 其他代码逻辑...
let fileName: string;
this.pdf.pdfName(pdfInfo).pipe(
  tap(res => fileName = res.fileName),
  concatMap(res => {
    if (!!res.fileName) {
      return this.pdf.getVersionPdfFile(res.fileName);
    }
    // 无文件名时先弹窗,再返回EMPTY终止流
    this.printEmptyAlert();
    return EMPTY;
  })
).subscribe(fileResponse => {
  // 只有存在文件名的分支才会走到这里
  const newBlob = new Blob([fileResponse], { type: "application/pdf" });
  const data = window.URL.createObjectURL(newBlob);
  const link = document.createElement('a');
  link.href = data;
  link.download = fileName;
  link.click();
  window.URL.revokeObjectURL(data);
});

补充说明

如果需要等用户关闭弹窗后再执行额外逻辑,可以直接返回MatDialog的afterClosed() Observable,示例如下:

concatMap(res => !!res.fileName ? 
  this.pdf.getVersionPdfFile(res.fileName) : 
  this.printEmptyAlert().afterClosed() // 要求printEmptyAlert返回MatDialogRef对象
)

不需要等待弹窗关闭的场景直接使用第一种方案即可。

内容的提问来源于stack exchange,提问作者FE-Deve

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 08:45:02