If I understand right, you want first upload the images and then save a Json containing, among other things, the list of urls corresponding to the images uploaded.
If this is the case, then I would proceed like this.
First I would transform Promises
to Observables
and create an array of Observables
corresponding to the requests to upload files, something like this
const uploadRequests$ = this.filesList.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
)
)
Now that you have an array of Observables, you can use the forkJoin
function of rxjs to create an Observable that will execute all the upload requests in parallel and emit, as result, an array containing all the responses.
Considering the way we have built the Observables, the responses will be either the url returned by the upload service or an error string.
The code would be something like
const urlsOrErrors$ = forkJoin(uploadRequests$)
Once urlsOrErrors$
emits, we are ready to execute the last service to save the Json. We need to make sure we execute such service only when urlsOrErrors$
has emitted, and so we use the concatMap
operator.
The final complete code would look something like this
const uploadRequests$ = this.filesList.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(urlsOrErrors => this.eventsService.update(
this.id,
this.form.value,
urlsOrErrors
))
)
If you are interested in common patterns for the use of rxjs with asynchronous services, you may find this article interesting.
CLICK HERE to find out more related problems solutions.