Angular发出http get请求,然后用get请求中的数据发出put请求



我想在AWS S3上上传多个图像。

首先在前端我上传图像并向用户显示图像预览,然后在循环内部我运行每次函数uploadFilesSimulator来上传每个图像。

prepareFilesList(files: Array<any>) {
for (const item of files) {
item.progress = 0;
this.files.push(item);
const reader = new FileReader();
reader.onload = (filedata) => {
item.url = reader.result + '';
}
reader.readAsDataURL(item);
this.uploadFilesSimulator(item);
}

}

首先,我向我的节点js API发出get请求。结果是密钥和url。然后在获取url后,我运行put请求,将图像添加到该url中。

uploadFilesSimulator(file: any) {
this.formService.getUploadUrl().subscribe(data => {
let upload = this.formService.uploadImage(data.url, file).subscribe(data => {
console.log(data)
}, err => console.log(err));
});

这是有效的,但我想避免嵌套的订阅。我应该使用什么rxjs运算符?

有三个运算符可以做到这一点:switchMapmergeMapconcatMap。更适合您的情况的是mergeMap,尽管对于您的特定情况不会有任何区别,因为this.formService.getUploadUrl()只会发出一个事件。

要了解更多详细信息,我建议这个优秀的网站:https://rxmarbles.com/

你可以这样使用它:

uploadFilesSimulator(file: any) {
return this.formService.getUploadUrl().pipe(
mergeMap(data => this.formService.uploadImage(data.url, file))
);
}

最新更新