I'm using Angular and would like to achieve following functionality.
In the form user can upload multiple images. On form submit I'd like to call upload endpoint with post method as many times as there are images (simple for loop). Each time call will return a response with link to google cloud platform storage for each image. Each time I would push the link to an array. Once it looped through all the images I'd like to finally submit post/patch request with the json data from the form and the array with links to google cloud platform.
At the moment I'm struggling with the asynchronous code. The request I would like to call at the very end is being triggered first, hence the image array with link to GCP is empty (event though the images are correctly uploaded to GCP, the upload of the images happen after the document was saved. From similar posts I understood that switchMap might be used but I don't know how to use it in this scenario
#update based on the @Picci comment, works for one image
I had to convert FileList to an array, I did it with
this.filesListArray = Array.from(this.filesList); and then implemented Picci solution:
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; }