简体   繁体   中英

RxJs multiple observables emitted from FileReader - collect as array

I'm building a filedrop platform, and hit an issue while reading Blob files from the FileReader API. Code flow is: get files from user in the upload service as an observable array, and generate a base64 string from the blob, to display in the browser.

Reader:

  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)
    })
  }

After resolving each of the files inside the forof, it will do a next to the service, that provides the final array for the DOM *ngFor | async loop:

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

What is the current results: The function emits the array length of Observable values 如这张img所示

What is the expected results: The function will emit one single array of all objects, according to this interface:

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

You are reinitializing src every time in for-of expression. Change this to 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);
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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