In my project to learn Angular. I ran a function that returns multiple values using RxJS.
The problem is that I found that using several subscribers it comes down to Subscribe hell ...
I tried with SwitchMap, it worked for the first returned value, but I have to use that last returned value to return other values. the problem is that it returns me undefined value. I think I misused switchMap ...
(I will put the 2 versions of my function) :
Working method but with multiple Subscribe :
addToCart2() {
const { quantity } = this.productForm.value;
const sessionCart = sessionStorage.getItem('cart_Session');
// Get Cart ID from SessionStorage
this.cartService
.retrieveCart(sessionCart!)
.subscribe(({ id: cart_ID }: Cart) => {
console.log('ID Cart : ', cart_ID);
console.log('Cart Already init');
// Add to cart method
this.cartService
.addToCart(cart_ID, this.product_ID, quantity, this.variant_Data)
.subscribe(
() => {
// Get current cart items to send Total items to Header
this.cartService.retrieveCart(cart_ID).subscribe((items) => {
this.cart_Items = items.line_items;
this.total_Items = items.total_unique_items;
this.cartService._totalItems$.next(this.total_Items);
});
// Modal Success TODO !!
},
(err) => {
console.log('Error in Request !!!', err);
},
() => {
console.log('Add to Cart Finish.');
}
);
});
}
Using SwitchMap but not working completely :
addToCart__NotWorking() {
// Test
const { quantity } = this.productForm.value;
const sessionCart = sessionStorage.getItem('cart_Session');
this.cartService
.retrieveCart(sessionCart!)
.pipe(
switchMap(({ id: cart_ID }) => {
console.log('SwitchMap', cart_ID);
return this.cartService.addToCart(
cart_ID,
this.product_ID,
quantity,
this.variant_Data
);
}),
switchMap(({ id: cart_ID }) => {
return this.cartService.retrieveCart(cart_ID);
})
)
.subscribe((values) => {
console.log('SwitchMap Final True : ', values);
});
}