c# - 如果在 Angular 的每个 forEach 循环中结果都成功,想要调用 this.addDispatchToReceive 方法
问题描述
我希望在每个循环中都有this.stockItemDispatch
值,this.addDispatchToReceive();
但在 foreach 循环完成后运行订阅时只获得最后一个股票值,例如,我们有一个循环运行 5 次并且this.stockItemDispatch
每次更新新股票但 .subscribe 仅针对第 5 个this.stockItemDispatch
值运行 5 次。
checkDispatchItemIsValid(): void {
const scannedBarcodes = [];
this.stockItemsDispatch.forEach(stock => {
this.stockItemDispatch = stock;
this.stockItems.forEach(function (item) { scannedBarcodes.push(item.identifier); });
let request = <ReceiveItemRequest>
{
identifier: stock.identifier,
identifiers: scannedBarcodes,
locationId: this.workstationInfoDetail.locationId
}
this.receiveItemsService.check(request)
.catch(e => {
this.notificationService.error(this.receive_error);
return Observable.of(e);
})
.subscribe(msg => {
if (Utils.isNullOrUndefined(msg)) {
this.showCannotAddToReceiveWarning = false;
this.cannotReceiveError = undefined;
this.addDispatchToReceive();
} else {
this.showCannotAddToReceiveWarning = true;
this.cannotReceiveError = msg;
this.notificationService.error(msg);
}
});
});
}
addDispatchToReceive() {
this.stockItems.push(this.stockItemDispatch);
this.canConfirmReceive = this.isStockItemsAdded;
this.clearBarcode();
}
解决方案
尽量避免嵌套订阅。它可能会导致您遇到的问题。相反,您可以使用 RxJSforkJoin
函数来组合多个 observables。尝试以下
checkDispatchItemIsValid(): void {
const requests = [];
const scannedBarcodes = [];
this.stockItemDispatch = stock;
this.stockItems.forEach((item) => {
scannedBarcodes.push(item.identifier);
});
this.stockItemsDispatch.forEach(stock => {
const request = < ReceiveItemRequest > {
identifier: stock.identifier,
identifiers: scannedBarcodes,
locationId: this.workstationInfoDetail.locationId
};
requests.push(this.receiveItemsService.check(request))
});
forkJoin(requests).subscribe(
messages => { // <-- response from each request as an array
messages.forEach(msg => {
if (Utils.isNullOrUndefined(msg)) {
this.showCannotAddToReceiveWarning = false;
this.cannotReceiveError = undefined;
this.addDispatchToReceive();
} else {
this.showCannotAddToReceiveWarning = true;
this.cannotReceiveError = msg;
this.notificationService.error(msg);
}
});
}
);
}
推荐阅读
- php - Laravel websockets连接失败
- mysql - 训练测试将 mysql 记录拆分为视图
- firebase - 'Future 类型的值
Function()' 不能分配给“用户”类型的变量 - r - Add gradient color within groups in ggplot2
- javascript - 谷歌应用脚本中全局变量的增量不起作用
- vue.js - vue js - Cannot read property 'use' of undefined
- python - Python:为什么 '.sort()' 没有按预期工作?
- excel - 检查一个组合框是否为空而另一个不是
- c# - 从 Unity 向 AWS Lambda 函数发送输入参数
- powershell - 如何使用 Format-Table cmdlet 显示所有属性