首页 > 解决方案 > 如果在 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();
    }

标签: c#.netangulartypescriptforeach

解决方案


尽量避免嵌套订阅。它可能会导致您遇到的问题。相反,您可以使用 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);
        }
      });
    }
  );
}

推荐阅读