angular - 如何在角度 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);
});
解决方案
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();
}
});
推荐阅读
- javascript - 使用 JavaScript BigQuery UDF 解密/解码 AES256
- python - numpy 数组;如何根据条件用另一个数组替换元素?
- sql - 将日期格式从 20180-01-01 转换为 201801
- regex - Perl 迭代正则表达式匹配的数量
- mongodb - MongoDB 中使用的 FS 大小意外增加
- reactjs - PowerApps 的 Material-ui?
- android - android导航架构库(nav_graph)的fragment之间的接口回调
- python - 如何使用 Selenium 或 Scrapy 抓取 AJAX 页面参数中的信息?
- android - 连接蓝牙医疗设备时启动 Android 应用程序
- wordpress - 将子域指向我网站的特定页面 - Wordpress 和 Godaddy