[英]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. 我正在构建一个Filedrop平台,并且在从FileReader API读取Blob文件时遇到问题。 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. 代码流是:以可观察的数组形式从上载服务中的用户获取文件,并从Blob生成base64字符串,以在浏览器中显示。
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 | 解决了论坛中的每个文件之后,它将在服务next
,该服务为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;
}
You are reinitializing src
every time in for-of
expression. 您每次都在for-of
表达式中重新初始化src
。 Change this to push
. 将其更改为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.