Как дождаться окончания подписки, прежде чем переходить к следующему индексу в цикле for в Angular 6 - PullRequest
0 голосов
/ 30 августа 2018

Я использую Angular 6.

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

Вот что я пытаюсь сделать, используя цикл for.

products: any;
processedItems: Array<any> = [];

private _processItem() {

  for (let i = 0; i < this.products.length; i++) {
    this.scraperService.scrapSingle(this.products[i].url).subscribe(
      res => {
        if (res.status.http_code === 200) {
          const properties = this.scraperService.processSingleProduct(res.contents);

          const p_item = {};
          p_item['info'] = this.products[i];
          p_item['properties'] = properties;

          this.processedItems.push(p_item);
        }
        console.log(res);
      }
    );
  }

console.log(this.products.length);
}

Но как ждать subscribe, прежде чем перейти к следующему индексу в цикле?

Ответы [ 2 ]

0 голосов
/ 30 августа 2018

Просто вставьте p_item в ваш массив с требуемым индексом, заданным i.

Например, вместо того, чтобы делать,

this.processedItems.push(p_item);

сделай это,

this.processedItems.splice(p_item, 0, i);

Это решит вашу проблему :)

0 голосов
/ 30 августа 2018

Используйте обещания вместо подписок rx.js с помощью метода toPromise. Возможно, вам придется сопоставить res с json. res.map (item => item.json ());

products: any;
processedItems: Array < any > =[];

private _processItem() {

    this.products.array.forEach(async (element) => {
        const res = await this.scraperService.scrapSingle(element.url).toPromise();
        if (res.status.http_code === 200) {
            const properties = this.scraperService.processSingleProduct(res.contents);

            const p_item = {};
            p_item['info'] = element
            p_item['properties'] = properties;

            this.processedItems.push(p_item);
        }
        console.log(res);
    });

    console.log(this.products.length);
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...