首页 > 解决方案 > 如何在角度 7 的 concatMap/switchMap 中使用检查条件

问题描述

我正在尝试下载 pdf 表单 API 响应。API-1 将返回文件名,并将文件名作为 API 的输入 - 2,我将下载 pdf。它适用于阳性病例。如果没有从 API - 1 返回的文件名,我不应该调用 API-2,而是必须告诉用户在 popupDialog 中不存在文件。

this.pdf.pdfName(pdfInfo).pipe(
      tap(res => fileName = res.fileName),
//Inside concatMap am not able to handle this condition (getVersionPdfFile-observable/printEmptyAlert - just a matdialog)
      concatMap(res => !!res.fileName ? this.pdf.getVersionPdfFile(res.fileName) : this.printEmptyAlert())
    ).subscribe(fileResponse => {
      var newBlob = new Blob([fileResponse], { type: "application/pdf" });
      const data = window.URL.createObjectURL(newBlob);
      var link = document.createElement('a');
      link.href = data;
      link.download = fileName;
      link.click();
      window.URL.revokeObjectURL(data);
    });

标签: angulartypescriptrxjsswitchmapconcatmap

解决方案


throwError您可以在没有文件名时抛出错误(使用)并在错误块中处理该错误:

进口throwError

import { throwError } from 'rxjs';


this.pdf.pdfName(pdfInfo).pipe(
   tap(res => fileName = res.fileName),
   concatMap(res => !!res.fileName ? this.pdf.getVersionPdfFile(res.fileName) : 
      throwError('No file name'))
   ).subscribe(fileResponse => {
        var newBlob = new Blob([fileResponse], { type: "application/pdf" });
        const data = window.URL.createObjectURL(newBlob);
        var link = document.createElement('a');
        link.href = data;
        link.download = fileName;
        link.click();
        window.URL.revokeObjectURL(data);
     }, (error) => {
        // Handle error here
        if(error === 'No file name'){
          this.printEmptyAlert();
        }
 });

推荐阅读