首页 > 解决方案 > 在可观察管道内使用 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 的方式)

标签: angulartypescript

解决方案


您可以只使用 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);
    }));
}

推荐阅读