As I continue to delve into the world of rxjs, I've encountered an issue with managing multiple subscriptions. Specifically, I'm struggling to extract an ID from a response in order to correctly associate photos with products.
create(product) {
this.api.createProduct(product).subscribe(product => {
product.photos.forEach(photo => {
photo.productId = product.id;
this.api.addPhoto(photo).subscribe();
});
});
While my current solution is functional, I understand that it's not the most efficient approach. I've heard that utilizing mergeMap and combineLatest could be more effective, but I'm unsure how to implement them properly.
Update 1
Improved solution
create(productForm) {
this.api.createProduct(productForm).pipe(
mergeMap(photo => {
return combineLatest([
productForm.photos.map(photo => {
this.api.addPhoto({...photo, productId: product.id})//.subscribe()
})
]);
).subscribe();
}
Despite this attempted improvement, I still encountered challenges actually adding photos using this method. It only worked when I included subscribe within addPhoto.
Update 2
Revised solution
create(productForm) {
this.api.createProduct(productForm).pipe(
mergeMap(photo => {
const photos = [];
productForm.photos.map(photo => {
photos.push(this.api.addPhoto({...photo, productId: product.id}));
});
return combineLatest([...photos]);
})
).subscribe();
}
Finally, by making these adjustments, I have managed to successfully achieve the desired functionality for adding photos.