繁体   English   中英

RxJs从FileReader发出多个可观察对象-收集为数组

[英]RxJs multiple observables emitted from FileReader - collect as array

我正在构建一个Filedrop平台,并且在从FileReader API读取Blob文件时遇到问题。 代码流是:以可观察的数组形式从上载服务中的用户获取文件,并从Blob生成base64字符串,以在浏览器中显示。

读者:

  async getFileList(files: File[]) {
    let src!: IStoryFile[];
    for (const f of files) {
      const blob = await this.readFileBlob(f)
      src = [{ file: f, src: blob }]
    }
    this.uploadSrv.setFilesUpload(src);
  }

  readFileBlob(file: File): Promise<any> {
    return new Promise((resolve, _) => {
      const reader = new FileReader()
      reader.onloadend = (e) => {
        resolve(reader.result)
      }
      reader.readAsDataURL(file)
    })
  }

解决了论坛中的每个文件之后,它将在服务next ,该服务为DOM * ngFor |提供最终数组。 异步循环:

protected files$!: Observable<IStoryFile[]>;
...
this.files$ = this.uploadSrv.getFilesUpload$()
      .pipe(
        tap(val => console.log(val)),
      )

当前结果是什么:函数发出可观察值的数组长度 如这张img所示

预期的结果是什么:该函数将根据此接口发出所有对象的单个数组:

export interface IStoryFile {
  file: File;
  src?: string | ArrayBuffer | null;
}

您每次都在for-of表达式中重新初始化src 将其更改为push

  async getFileList(files: File[]) {
    let src!: IStoryFile[] = []; // Initialize
    for (const f of files) {
      const blob = await this.readFileBlob(f)
      src.push({ file: f, src: blob }); // Push new object
    }
    this.uploadSrv.setFilesUpload(src);
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM