如何在 concatMap/switchMap in angular 中使用检查条件 7

How to use check condition with in concatMap/switchMap in angular 7

我正在尝试下载 pdf 表单 API 回复。 API-1 将 return 文件名,用文件名作为输入到 API - 2,我将下载 pdf。 它适用于阳性病例。如果没有文件名 returned 来自 API - 1,我不应该调用 API-2,而是我必须告诉用户弹出对话框中不存在文件。

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);
    });

您可以在没有文件名时抛出错误(使用 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();
        }
 });