在可观察管道内使用 await

Kam*_*ski 3 typescript angular

我的角度应用程序我想下载 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);
    }));
}
Run Code Online (Sandbox Code Playgroud)

但得到编译错误

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.
Run Code Online (Sandbox Code Playgroud)

所以问题是我async-await在里面使用pipe/ map如何解决?(我不想找到允许使用 async-await 并返回 observable 的方法)

Ted*_*rne 9

您可以使用 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);
    }));
}
Run Code Online (Sandbox Code Playgroud)