Reputation: 160
I want to upload multiple images on AWS S3.
First on frontend i upload images and show the preview of images to the user, then inside for loop i'm running every time function uploadFilesSimulator to upload every image.
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);
}
}
First i make get request to my node js API. The result is key and url. Then after url is fetched I run put request to add image to that 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));
});
This is working but i want to avoid nested subsriptions. What rxjs operator should i use ?
Upvotes: 0
Views: 156
Reputation: 31825
Three operators can do that: switchMap
, mergeMap
, and concatMap
. The more appropriate for your case is mergeMap
, even though for your particular case there won't be any difference because this.formService.getUploadUrl()
will only emit one event.
For more details, I suggest this excellent web site: https://rxmarbles.com/
You can use it like this:
uploadFilesSimulator(file: any) {
return this.formService.getUploadUrl().pipe(
mergeMap(data => this.formService.uploadImage(data.url, file))
);
}
Upvotes: 1