Reputation: 407
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
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;
}
Upvotes: 0
Views: 757
Reputation: 425
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);
}
Upvotes: 2