等待可观察到的for循环完成,然后继续在Angular 5中循环 [英] Wait for observable in for loop to finish before continuing loop in Angular 5

查看:74
本文介绍了等待可观察到的for循环完成,然后继续在Angular 5中循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在遍历对象数组(称为项目).forEach循环包含一个返回可观察值的服务调用.我试图等待处理数组中的下一个项目,直到循环中的可观察完成.我应该使用什么?我已经尝试过forkJoin.

I'm looping through an array of objects (called projects). The forEach loop contains a service call that returns an observable. I'm trying to wait to process the next project in the array until the observable within the loop completes. What should I use? I tried forkJoin already.

projects
    .forEach(project => {
        this.imageService.getProjectImages(project.projectId.toString(), true, true, undefined)
            .catch(err => observer.error(err))
            .finally(() => {
                // process next project
            })
            .subscribe((image: FileRepresentation) => {
                data.image = image;
                this.getSlide(project, data);
            });
})

推荐答案

我最终想出了一个解决方案.关键是要使用递归调用的第二个函数.

I eventually figured out a solution. The key is to use a second function that is called recursively.

将所有项目和第一个项目的索引传递给getImagesForProject.在收到第一个项目的所有图像后,请检查imageCount是否小于maxImages.如果是,请递归调用getImagesForProject直到达到限制.

Pass all projects and the first project's index to getImagesForProject. Once all images have been received for the first project, check to see if the imageCount is less than maxImages. If yes, call getImagesForProject recursively until the limit is reached.

this.getImagesForProject(projects, 0, 5);

getImagesForProject(projects: Project[], index: number, maxImages: number = 5, imageCount?: number) {
    this.imageService.getProjectImages(projects[index].projectId.toString(), true, true, undefined)
    .finally(() => {
        if(imageCount < maxImages) {
            this.getImagesForProject(projects, data, (index + 1), imageCount);
        }
    })
    .subscribe(image => {
        imageCount++;
        data.image = image;
        this.getSlide(projects[index], data);
    });
}

这篇关于等待可观察到的for循环完成,然后继续在Angular 5中循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆