首页 > 解决方案 > RXJS Angular - 如何在包含可观察对象的 foreach 循环结束时调用函数?

问题描述

this.attachmentList.forEach((attachment, i) => {
    this.service.getPageOfAttachment().flatMap(response =>
        this.service.download((JSON.parse(response['Content']).mediaUrl)))
        .subscribe(response => {
            }, error => (console.log(error)),
            () => {
                if (i > this.attachmentList.length - 1) this.getPdfSharp(pdfSharpByteArray, attachment.entityName, i);
            })
})

在 foreach 循环结束时,我正在检查“i”的值,如果它大于列表长度,则调用该函数。这样做的问题是,由于我在循环内订阅,所以 I 的值并不总是正确的顺序,并且该函数被提前调用。如何遍历包含订阅的 foreach 循环,然后在循环和订阅完成时调用我的函数?

标签: javascripttypescriptrxjsangular5angular-httpclient

解决方案


你想过forkJoin吗?可能不是最干净的,但我认为它可以工作。这也可以帮助等待 foreach 内的可观察订阅结束


推荐阅读