Angular在foreach内部订阅不返回承诺

时间:2020-03-22 16:48:11

标签: angular typescript

我正在foreach语句中逐行更新。我需要等待foreach循环中的所有项目都已更新,然后才需要进行一些定型。下面的方法可以在服务中使用,但是“ wait.then”永远不会被击中。有更好的方法吗?

var wait = new Promise((resolve, reject) => {
  this.myArray.Items.forEach(t => {
    this.service.UpdateItems(t).subscribe(
      () => {},
      err => this.alert(err),
      () => this.app.tick(),
    );
  });
});
wait.then(() => {
  // Wait until the foreach finished
  console.log(complete);
});

1 个答案:

答案 0 :(得分:1)

您不需要使用Promises。您可以使用forkJoin做这样的事情:

const sources = this.myArray.Items.map(item => {
  return this.service.UpdateItems(item).pipe(
    tap({
      complete: () => this.app.tick(), // not sure for what you're using this
      error: err => this.alert(err),
    }),
  );
});

forkJoin(sources)
  .pipe(finalize(() => console.log('do something')))
  .subscribe();