【发布时间】:2020-10-28 16:45:50
【问题描述】:
我正在使用 Angular 并希望实现以下功能。
用户可以在表单中上传多张图片。在表单提交时,我想用 post 方法调用上传端点的次数与图像的次数一样多(简单的 for 循环)。每次调用都会返回一个响应,其中包含每个图像的谷歌云平台存储链接。每次我都会将链接推送到数组。一旦它遍历所有图像,我想最终提交 post/patch 请求,其中包含表单中的 json 数据和带有指向谷歌云平台链接的数组。
目前我正在努力处理异步代码。我想在最后调用的请求首先被触发,因此带有 GCP 链接的图像数组为空(尽管图像已正确上传到 GCP,但图像的上传发生在文档保存后。从类似的帖子我知道可能会使用 switchMap 但我不知道如何在这种情况下使用它
#update 基于@Picci 评论,适用于一张图片
我必须将 FileList 转换为数组,我用
this.filesListArray = Array.from(this.filesList);
然后实施Picci方案:
onSave(){
if(this.form.invalid) {
console.log(this.form)
return;
}
const uploadRequests$:Observable<[string]> = this.filesListArray.map(file =>
from(this.uploadService.upload(file)) // transform Promise to Observable using the rxjs 'from' function
.pipe(
map(response => response['filePath']),
catchError(err => of(`Error while uploading ${file}`)) // if there is an error, return the error
)
);
const urlsOrErrors$ = forkJoin(uploadRequests$);
urlsOrErrors$.pipe(
concatMap(result => this.eventsService.update(this.id, this.form.value, result))
).subscribe(() => {
this.form.reset();
this.router.navigate([this.id]);
})
.closed;
}
【问题讨论】: