angular - 在可观察管道内使用 await
问题描述
我的角度应用程序我想下载 pdfBlob
并处理它以获得Uint8Array
. 我想在服务中做这件事,这将返回我 rxjsObservable<Uint8Array>
但我不能。我写下面的代码
public loadBinaryPDF(url): Observable<Uint8Array> {
return this.httpClient.get(url, { responseType: 'blob' }).pipe(map(async blob => {
let arrayBuff = await new Response(blob).arrayBuffer(); // some await here..
return new Uint8Array(arrayBuff);
}));
}
但得到编译错误
ERROR in src/services/api-companies.service.ts(454,9): error TS2322:
Type 'Observable<Promise<Uint8Array>>' is not assignable to type 'Observable<Uint8Array>'.
Type 'Promise<Uint8Array>' is missing the following properties from type 'Uint8Array':
BYTES_PER_ELEMENT, buffer, byteLength, byteOffset, and 25 more.
所以问题是我async-await
在里面使用pipe
/ map
。如何解决?(我不想找到允许使用 async-await 并返回 observable 的方式)
解决方案
您可以只使用 asswitchMap
而不是地图。
public loadBinaryPDF(url): Observable<Uint8Array> {
return this.httpClient.get(url, { responseType: 'blob' }).pipe(switchMap(async blob => {
let arrayBuff = await new Response(blob).arrayBuffer();
return new Uint8Array(arrayBuff);
}));
}
推荐阅读
- r - 如何根据 R 中的某些模式导入大量数据集
- sql - 输入“来自”不匹配。期待:'on','using' 在 Athena
- .net - 更新多目标项目的包引用
- c# - 如何强制 Visual Studio 2022 创建带有命名空间和类的控制台项目(就像过去的好日子一样)?
- flutter - 我们可以与从事同一项目的其他开发人员共享我的“API KEY”吗?
- c - Windows API:可以以编程方式移动 Windows IME 输入框吗?
- multilingual - 如何削减 Huggingface 上共享的预训练多语言模型?
- css - 未检测到 xpath 跨度
- batch-file - 批处理文件从另一个文件的文件中添加一列,第一个字段匹配,第二个文件具有大列
- terraform - 在 oci 中获取子网值时出现 Terraform 错误