2 回答
TA贡献1805条经验 获得超10个赞
考虑以下辅助函数,它接受 aBlob作为参数并返回 an Observable<string>:
function blobToBase64(blob: Blob): Observable<string> {
return new Observable<string>(observer => {
const reader = new FileReader();
reader.onerror = observer.error;
reader.onabort = observer.error;
reader.onload = () => observer.next(reader.result as string);
reader.onloadend = observer.complete;
reader.readAsDataURL(blob);
return {
unsubscribe: reader.abort
}
})
}
用法:
declare const fileObservable: Observable<File>;
fileObservable
.pipe(switchMap(blobToBase64))
.subscribe(base64 => console.log(base64))
TA贡献1831条经验 获得超4个赞
没有现成的方法可以将此加载的事件转换为 rxjs observable。你必须创建自己的运算符。
export const dataUrlToObs = myFile => new Observable<string | ArrayBuffer>(subscriber => {
const reader = new FileReader();
reader.readAsDataURL(myFile);
reader.onload = () => {subscriber.next(reader.result); subscriber.complete(); };
reader.onerror = () => subscriber.error(reader.error);
return () => reader.abort(); // cancel function in case you unsubscribe from the obs
}
稍后可以这样使用:
..chain
switchMap(myFile => dataUrlToObs(myFile)),
tap(resultStrOrArrayBuf => {
if (!(resultStrOrArrayBuf instanceof ArrayBuffer)) {
..do something with resultStrOrArrayBuf
}
})
添加回答
举报