I have a POST request to create a Movie that returns an Observable, the result of this request returns me an ID that I need to make two further requests using this ID to add a Director & Movie Images.
I have the following call, it works perfectly when it comes to adding the Director however when I get to the second flatMap I'm unable to loop through the images to POST them without adding a subscribe on the end.
Is there a better way to do this? I have tried switchMap, mergeMap and map but I cannot get the second request to fire without the subscribe.
this.Movie.createMovie(movie).pipe(
map((movie: Movie) => {
return movie;
}),
switchMap((movie: Movie) => this.movieRepository.postDirector(director, movie.id)),
flatMap((director: Director) => {
return movieImages.map((image) => {
return this.movieRepository.addMovieImage(image, director.movie_id).subscribe()
});
})
).subscribe({
next: (response: any) => {
console.log(response)
}
})
flatMap
resolves an observable returned from the callback, but your callback returns an array. You need e.g.forkJoin
to turn an array of observables into an observable of an array. – jonrsharpe