美好的一天。
我遇到了如何正确完成这项工作的问题,问题是我有一个订阅函数需要在 For 循环内解析,如下所示:
if (item.paquete == 1) {
this.productoService.getInfoPaquetes(item.sku).subscribe(paquetaxo =>{
this.paquetaxos = paquetaxo;
for (let index = 0; index < this.paquetaxos.length; index++) {
let lineasLocal = {
salesQuotationNumber: null,
dataAreaId: "lin",
itemNumber: this.paquetaxos[index].sku,
requestedSalesQuantity: Number(this.paquetaxos[index].cantidad),
shippingWarehouseId: "CHIHCONS",
fixedPriceCharges: 0,
salesTaxGroupCode: "VTAS",
stF_Category: null,
inventoryLotId: null,
orderedSalesQuantity: 0,
salesOrderNumber: null,
descripcionLinea: null,
usuario: null,
salesPrice: Number(this.paquetaxos[index].precio_total),
ShippingSiteId: "CHIH",
LineDiscountPercentage: 0
};
this.lineas.push(lineasLocal);
}
})
}
我们有一家商店,代码需要检查购物车上的商品是否是包含各种商品的“促销包”,因此循环会生成其中包含的商品的数组。
这里的问题是,由于某种原因,订阅不会等到所有产品完成检查并且数组被发送为空到创建订单的 API。
我知道您可以拥有需要在 Promise 内等待的代码,以便它等待解析才能正常工作,但这次它不能这样做,因为它位于 for 循环内。
我创建了一个解决方法,将下一个操作放入计时器功能中,以便它等待 3 秒来完成循环并正确填充数组,但显然有时如果填充时间超过 3 秒,它可能会失败,取决于顾客购物车上有多少商品。
有没有办法让 for 循环上的订阅等到完成后再继续下一个代码块?
感谢您阅读它。
您考虑过使用 rxjs 和 forkJoin 吗?文档在这里:https://www.learnrxjs.io/learn-rxjs/operators/combination/forkjoin
使用您的代码,这将是这样的:
import { forkJoin } from 'rxjs';
然后
if (item.paquete == 1) {
this.productoService.getInfoPaquetes(item.sku).subscribe(paquetaxo => {
this.paquetaxos = paquetaxo;
const observables = this.paquetaxos.map(paquetaxoItem => {
return this.productoService.getInfoPaquetes(paquetaxoItem.sku);
});
forkJoin(observables).subscribe(paquetaxosData => {
for (let index = 0; index < paquetaxosData.length; index++) {
let lineasLocal = {
salesQuotationNumber: null,
dataAreaId: "lin",
itemNumber: this.paquetaxos[index].sku,
requestedSalesQuantity: Number(this.paquetaxos[index].cantidad),
shippingWarehouseId: "CHIHCONS",
fixedPriceCharges: 0,
salesTaxGroupCode: "VTAS",
stF_Category: null,
inventoryLotId: null,
orderedSalesQuantity: 0,
salesOrderNumber: null,
descripcionLinea: null,
usuario: null,
salesPrice: Number(this.paquetaxos[index].precio_total),
ShippingSiteId: "CHIH",
LineDiscountPercentage: 0
};
this.lineas.push(lineasLocal);
}
// Code that depends on this.lineas here.
});
});
}