Angular 5 - 具有异步数据的同步循环

时间:2018-04-04 16:54:23

标签: angular asynchronous rxjs

我在服务中有一个迭代与for循环同步的方法。在这个for循环中,我有一个异步调用,我想只在异步调用完成时继续循环。我是否需要某种发送到异步调用值的均衡器? Couse我现在为了一个事实异步调用将打开我不同的线程,所以for循环迭代,甚至没有等待 如果调用完成。 这是我的服务方法:

private mapHeroTypeToDisplayHeroType(heroList: TroopsHeroesAndSpellType[]): Observable<HeroDisplay[]> {
    const heroesWithImgArray: HeroDisplay[] = [];
    for (const hero of heroList) {
        Object.keys(Heroes).filter(HeroesKey => {
            if (hero.name === Heroes[HeroesKey]) {
                Object.keys(HeroesImg).filter(HeroesImgKey => {
                    if (<Heroes>HeroesKey as string === <HeroesImg>HeroesImgKey as string) {
                        this.storage.ref(HeroesImg[HeroesImgKey]).getDownloadURL().subscribe((data: HeroesImg) => {
                            let heroObj = {
                                name: hero.name,
                                level: hero.level,
                                maxLevel: hero.maxLevel,
                                village: hero.village,
                                heroImg: data
                            };
                            heroesWithImgArray.push(heroObj);
                        });
                    }
                });
            }
        });
    }
    return Observable.of(heroesWithImgArray);
}

1 个答案:

答案 0 :(得分:0)

解决方案是 - Observables forkJoin - 它看起来像这样:

  private mapHeroTypeToDisplayHeroType(heroList: TroopsHeroesAndSpellType[]): Observable<HeroDisplay[]> {
const observables: Observable<HeroDisplay>[] = [];
let heroObj: HeroDisplay;
for (const hero of heroList) {
  for (const heroesKey in Heroes) {
    if (hero.name === Heroes[heroesKey]) {
      for (const heroesImgKey in HeroesImg) {
        if (<Heroes>heroesKey as string === <HeroesImg>heroesImgKey) {
         const singleHeroImgObservable =
           this.storage.ref(HeroesImg[heroesImgKey]).getDownloadURL().map((data: HeroesImg) => {
            return  heroObj = {
              name: hero.name, level: hero.level, maxLevel: hero.maxLevel, village: hero.village, heroImg: data
            };
          });
          observables.push(singleHeroImgObservable);
        }
      }
    }
  }
}
return Observable.forkJoin(observables);

}