【发布时间】:2019-11-19 14:46:43
【问题描述】:
我的 Angular 应用程序我想将 pdf 下载为 Blob 并处理它以获得 Uint8Array。我想在服务中执行此操作,这将返回我 rxjs Observable<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.
所以问题是我在pipe/map 中使用了async-await。 如何解决?(我找不到允许使用 async-await 并返回 observable 的方法)
【问题讨论】:
-
为什么要使用async/await? rxjs API 不能和
Promise一起使用? -
您的 map 函数是异步的,它将返回值再次包装为 Promise。结果你得到
Observable<Promise<Uint8Array>>。我个人不建议混合使用 Promise 和 Observables。做一件事或另一件事。 -
@MoxxiManagarm 你知道将
Blob转换为arrayBuffer的更简单的替代方法吗? -
@HTN 你从哪里听到的?据我所知,这根本不是真的——你有任何消息来源支持这一说法吗?
标签: angular typescript