在嵌套for循环完成后,Typescript执行代码

时间:2017-11-24 08:49:21

标签: javascript angular typescript synchronization

我有一个嵌套的for循环,内部循环也以角度2

进行服务调用
public populateData: any[] = [];

let appCounter = 0;
this.list.forEach(data => {       <---- outer loop
    this.service.getSubs(data.id).subscribe(res => { <---- backend call to get data
            let subscriptions = res.subscriptions;

            subscriptions.forEach(subscription => {
                if(condition){
                    this.populateData.push(subscription);   
                }
            });     
    }); 
    appCounter++;
    if(appCounter == this.list.length){
        console.log('--------- subscriptionList ----------');
        console.log(this.populateData);
    }
});

我想通过完全执行外部循环填充populateData变量后调用方法。

目前,它在控制台中给我空数组,因为外部循环完全执行,而内部HTTP调用仍处于未决状态。

1 个答案:

答案 0 :(得分:1)

forkJoin可能会有运气:

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/forkJoin';

public populateData: any[] = [];
public observables: any[] = [];

this.list.forEach(data => { 
  this.observables.push(this.service.getSubs(data.id)); 
});

Observable.forkJoin(this.observables)
  .subscribe(res => {
    res.forEach((element:any) => {
      let subscriptions = element.subscriptions;
      subscriptions.forEach(subscription => {
        if(condition){
          this.populateData.push(subscription);   
        }
      });
      console.group('subscription list');
      console.log(this.populateData);
    });
  })