Хотите вызвать метод this.addDispatchToReceive, если результат успешен в каждом forEach l oop в Angular - PullRequest
0 голосов
/ 18 июня 2020

Я хочу this.stockItemDispatch значений в this.addDispatchToReceive(); в каждом l oop, но получаю только последнее значение запаса, поскольку подписка запускается после завершения цикла foreach, например, у нас есть al oop, который выполняется 5 раз, а this.stockItemDispatch обновляется каждый время с новыми акциями, но .subscribe запускается 5 раз только для 5-го this.stockItemDispatch значений.

    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();
    }

1 Ответ

0 голосов
/ 18 июня 2020

Старайтесь избегать вложенных подписок. Это может привести к проблемам, с которыми вы столкнулись. Вместо этого вы можете использовать функцию Rx JS forkJoin для объединения нескольких наблюдаемых. Попробуйте следующее

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);
        }
      });
    }
  );
}
...