【问题标题】:Typescript execute code after nested for loop is completed嵌套for循环完成后打字稿执行代码
【发布时间】:2017-11-24 17:43:37
【问题描述】:

我有一个嵌套的 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 调用仍处于挂起状态。

【问题讨论】:

  • 似乎promises 在这里为您服务,更准确地说是Promise.all。或者您可以通过在回调中增加一个变量并测试是否所有响应都到达了老派的方式,这样您就可以触发其余的代码(所有这些都在回调中,除了不需要在步骤)
  • 如果我在getSubs 服务调用中打印appCounter 变量,它打印的值等于this.list 的大小,因为即使是第一次服务调用,外部循环也会被执行并且appCounter 会递增。
  • 计数器增量及其值的测试必须在异步调用的回调中才能工作

标签: javascript angular typescript synchronization


【解决方案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);
    });
  })

【讨论】:

  • 试过了,但我得到了'subscriptions' does not exist on type '{}',如果我这样做了console.log(element),数据就在那里,但控制台中有i的图标,上面写着Values below are just evaluated now
  • 尝试将res.forEach(element...更改为res.forEach((element:any)...
  • 此次更改后订阅即将到来,有没有办法在res.forEach((element.. 中获取data 变量
  • 我找到了一种解决方法,可以在 res.forEach 的对象中获取 data。感谢您的解决方案
猜你喜欢
  • 1970-01-01
  • 2021-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-26
  • 1970-01-01
  • 2018-01-20
  • 1970-01-01
相关资源
最近更新 更多