在我學習 Angular 的專案中。我運行了一個使用 RxJS 回傳多個值的函式。
問題是我發現使用多個訂閱者歸結為訂閱地獄......
我嘗試使用 SwitchMap,它適用于第一個回傳值,但我必須使用最后一個回傳值來回傳其他值。問題是它回傳給我未定義的值。我想我誤用了 switchMap ...
(我將把我的功能的 2 個版本):
作業方法但有多個 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.');
}
);
});
}
使用 SwitchMap 但不能完全作業:
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);
});
}
uj5u.com熱心網友回復:
是的,您似乎在 switchMaps 之間丟失了 car_id,return this.cartService.addToCart沒有回傳 id,至少根據您的嵌套訂閱,您改為使用您傳遞給 的相同購物車 id addToCart。您可以做的是使用,mapTo因為您似乎不需要this.cartService.addToCart. 所以,你可以這樣做:
switchMap(({ id: cart_ID }) => {
console.log('SwitchMap', cart_ID);
return this.cartService.addToCart(
cart_ID,
this.product_ID,
quantity,
this.variant_Data
).pipe(
mapTo({ id: cart_ID }) // here, now it returns the id!
);
}),
// .....
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/345439.html
上一篇:為什么流不發出變化?
