Остановка функции до тех пор, пока я не получу ответ API, затем возобновлю работу с остальным кодом - PullRequest
0 голосов
/ 09 марта 2020

У меня действительно есть проблемы с этим. Используемая им функция проверяет счетчик для каждого компонента массива, чтобы преобразовать массив в переменную только в том случае, если счетчик меньше, чем состояние числа y.

Проблема в том, что когда counter достигает предела y, отправляя переменную в API, и в успешном ответе я перезапускаю счетчик и очищаю переменную, чтобы сделать все заново.

Моя проблема в том, когда я отправляю первое, которое принимает API время, чтобы дать мне ответ, но остальная часть массива, которую я проверяю, уже прошла, и потому что я только сбрасываю счетчик в ответе, только один раз, когда к API обращаются

Код, который я сейчас использую:

cargaLotes() {
  let totallengthchange = this.Arraydata.length;

  this.cargaloader = true;
  this.Step = true;
  for (const values of this.Arraydata) {
    this.check(values);
  }

  // this.lenghtloader = this.Arraydata.length;
  let lengthafterPush;
  let lengthdivided;
  let lengthdisplay;
  const porcetaje = 1;
  const totaldisplay = 100;
  let lengtharray = this.Arraydata.length;
  const lengtharraystatico = this.Arraydata.length;
  const temp: any = this.Arraydata;
  if (this.Step === true) {
    let contador1 = 0;
    (contador1 < 500) {
      temp.forEach(data => {
        if (contador1 < 499) {
          this.arraytosend.push(data);
          contador1 = contador1 + 1;
          if (contador1 === lengtharray) {
            this.service.(service)(this.arraytosend).subscribe(resp => {
              this.notificacion.showNotification('top', 'right', 'Se Cargaron los Productos', 'warning');
              this.getProductoPrice();
              this.lenghtloader = 100;
            }, err => {
              this.notificacion.showNotification('top', 'right', 'Ocurrio un error', 'danger');
            });

          }
          if (contador1 === 499) {
            this.arraytosend.push(data);
            this.service.(service)(this.arraytosend).subscribe(resp => {
              console.log(resp);
              totallengthchange = totallengthchange - 500;
              lengthafterPush = totallengthchange;
              console.log(lengthafterPush);
              lengthdivided = lengthafterPush / lengtharraystatico;
              lengthdisplay = porcetaje - lengthdivided;
              this.lenghtloader = lengthdisplay * totaldisplay;

            }, err => {
              console.log(err);
              this.notificacion.showNotification('top', 'right', 'Ocurrio un error', 'danger');
            });
            lengtharray = lengtharray - 500;
            this.arraytosend = [];
            contador1 = 0;
          }


        }

      });
    }
  } else {
    this.ArraydataDuplicates = [];
    for (const values of this.Arraydata) {
      this.showDuplicates(values);
    }
    this._snackBar.open(`El Archivo Contiene Productos que ya han sido registrados!.`, 'Ocultar', {
      duration: 5000
    });

  }

}

1 Ответ

0 голосов
/ 09 марта 2020

Проще говоря, ваш код буферизует значения в массив, который затем отправляется в API. Это будет повторяться до тех пор, пока в массиве не останется значений. Вы отправляете пакеты значений в API.

Я приведу очень упрощенный c пример типа шаблона, который вы могли бы использовать ниже. Я проигнорировал множество побочных эффектов, которые выполняет ваш код - они должны быть достаточно простыми для интеграции после сортировки основного шаблона.

component.ts

private batchSize = 500;
private data: number[];

// handle some event that determines when the batches should be sent
onSend() {
  // assume this.data has been set somewhere

  this.sendBatches().subscribe(() => {
    console.log('done');
  });
}

private sendBatches(): Observable<any> {
  // splice the data to get the batch of data to be sent
  const batch: number[] = this.data.splice(0, this.batchSize);
  if (batch.length === 0) {
    return of(null);
  }    

  return this.sendData(batch).pipe(
    // recursive chain the observable calls
    switchMap(() => this.sendBatches(batchSize))
  );
}

private sendData(data: number[]): Observable<any> {
  // mock call to the API
  return of({}).pipe(delay(1000));
}

DEMO : https://stackblitz.com/edit/angular-60605895

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...