Rxjs 链将 observable<File> 转换为 observable<string>

我有一个工作代码将我的 File 对象转换为 base64:


let reader = new FileReader();

     reader.readAsDataURL(myFile);

     reader.onload = () => {

         let resultStrOrArrayBuf = reader.result;

         if (!(resultStrOrArrayBuf instanceof ArrayBuffer)) {

            ..do something with resultStrOrArrayBuf

         }

    };

但是我现在必须将这部分集成到现有的 rxjs 链中。在链中,我收到 File 对象,并希望继续转换的 Base64 结果。然而,转换是在onload事件的帮助下完成的。有什么方法可以将此事件转换为新的可观察对象并将其传递到链吗?


收到一只叮咚
浏览 127回答 2
2回答

holdtom

考虑以下辅助函数,它接受 aBlob作为参数并返回 an Observable<string>:function blobToBase64(blob: Blob): Observable<string> {&nbsp; return new Observable<string>(observer => {&nbsp; &nbsp; &nbsp; const reader = new FileReader();&nbsp; &nbsp; &nbsp; reader.onerror = observer.error;&nbsp; &nbsp; &nbsp; reader.onabort = observer.error;&nbsp; &nbsp; &nbsp; reader.onload = () => observer.next(reader.result as string);&nbsp; &nbsp; &nbsp; reader.onloadend = observer.complete;&nbsp; &nbsp; &nbsp; reader.readAsDataURL(blob);&nbsp; &nbsp; &nbsp; return {&nbsp; &nbsp; &nbsp; &nbsp; unsubscribe: reader.abort&nbsp; &nbsp; &nbsp; }&nbsp; })}用法:declare const fileObservable: Observable<File>;fileObservable&nbsp; .pipe(switchMap(blobToBase64))&nbsp; .subscribe(base64 => console.log(base64))

慕容708150

没有现成的方法可以将此加载的事件转换为 rxjs observable。你必须创建自己的运算符。export const dataUrlToObs = myFile => new Observable<string | ArrayBuffer>(subscriber => {&nbsp; const reader = new FileReader();&nbsp; reader.readAsDataURL(myFile);&nbsp; reader.onload = () => {subscriber.next(reader.result); subscriber.complete(); };&nbsp; reader.onerror = () => subscriber.error(reader.error);&nbsp; return () => reader.abort(); // cancel function in case you unsubscribe from the obs}稍后可以这样使用:..chainswitchMap(myFile => dataUrlToObs(myFile)),tap(resultStrOrArrayBuf => {&nbsp; &nbsp;if (!(resultStrOrArrayBuf instanceof ArrayBuffer)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;..do something with resultStrOrArrayBuf&nbsp; &nbsp;}})
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript