我有這個 reloadProducts 功能,我用它來重新加載我購物車中的產品。我有 2 個模型,一個是 CartProduct,另一個是 Product。CartProduct 有一個名稱,我將其與我的服務中的函式一起使用,以獲取匹配的產品。
現在,當我映射 cartProduct 時,我想檢查 CartProduct 是否將布林值 (mixMatch) 設定為 true,如果是,則將 Products mixMatch 布林值設定為 true,否則設定為 false。在下面的代碼中,我用我嘗試過的地方評論了#HERE,但它不起作用。
誰能幫助我或指導我如何做到這一點?
@HostListener('window:storage')
reloadProducts() {
this.cartProducts = Array.from(this.cartService.getProducts());
this.products = undefined;
this.totalPrice = undefined;
this.producers = undefined;
this.producerNames = [];
forkJoin(
this.cartProducts.map(cartProduct => {
let result = this.productService.getProduct(cartProduct.product_name);
// HERE
result.subscribe((product) => {
if (cartProduct.mixMatch) {
product.mixMatch = true;
}
else if (!cartProduct.mixMatch) {
product.mixMatch = false;
}
})
return result;
}
)
).pipe(
switchMap(productListDto => {
productListDto.map(product => {
if (this.producerNames.indexOf(product.producer_name) === -1) {
this.producerNames!.push(product.producer_name)
}
})
this.products = productListDto
this.mixMatchProducts = productListDto.filter(p => p.mixMatch)
return forkJoin(
this.producerNames.map(producerName => this.producerService.getProducerByName(producerName))
)
})
).subscribe(producers => this.producers = producers)
this.fetchTotalPrice();
}
uj5u.com熱心網友回復:
您希望該函式構成 rxjs 管道的一部分,所以我寧愿getProduct通過map管道傳輸結果。我會這樣做:
this.cartProducts.map(cartProduct =>
this.productService
.getProduct(cartProduct.product_name)
.pipe(
map((product) => {
product.mixMatch = cartProduct.mixMatch;
return product;
})
)
)
您還可以使用tap功能,您不需要回傳product.
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/522008.html
標籤:有角度的打字稿rxjs可观察的rxjs-observables
