我有一个嵌套的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调用仍处于未决状态。
答案 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);
});
})