在foreach里面等待observable订阅结束

时间:2018-06-06 13:09:45

标签: javascript typescript rxjs

我迭代一个对象数组,每次迭代我运行一个observable.subscribe,我如何确保所有订阅都完成,所以我可以调用另一个函数?

这是函数

calculaSimulacoesPorInscricao(){
    let lista = ["2019-01-01","2020-02-02","2021-01-01","2022-01-01","2023-01-01"];
    this.cliente.coberturas.forEach(cobertura => {
      cobertura.MovimentosProjetados = [];
      this._dataService.ObterSimulacao(cobertura.codigoInscricao,lista)
      .subscribe((data:any[])=>{
        data[0].simulacaoRentabilidadeEntities.forEach(simulacao =>{ 
          let movimento = {
            dataMovimento: '',
            valor: 1,
            imposto: 1,
            percentualCarregamento: 1,
            fundoCotacao: []
          };         
        movimento.dataMovimento = simulacao.anoRentabilidade;
        movimento.imposto = cobertura.totalFundos * simulacao.demonstrativo.demonstrativo[0].aliquota;
        movimento.percentualCarregamento = simulacao.valorPercentualCarregamento * (cobertura.totalFundos + (cobertura.totalFundos * simulacao.percentualRentabilidade));
        movimento.valor = cobertura.totalFundos + (cobertura.totalFundos * simulacao.percentualRentabilidade);
        cobertura.MovimentosProjetados.push(movimento);
        });
      })
    });
    this.calcularSimulacao();

  }

我需要在coberturas.foreach内完成所有订阅之后调用calcularSimulacao()。有什么提示吗?

2 个答案:

答案 0 :(得分:4)

您可以尝试将forkJoinonCompleted回调一起使用。见下文:

calculaSimulacoesPorInscricao() {
    let lista = [
        '2019-01-01',
        '2020-02-02',
        '2021-01-01',
        '2022-01-01',
        '2023-01-01'
    ];
    let all_obs = [];
    this.cliente.coberturas.forEach(cobertura => {
        cobertura.MovimentosProjetados = [];
        all_obs.push(
            this._dataService.ObterSimulacao(cobertura.codigoInscricao, lista).pipe(
                map(
                    (data: any[]) => {
                        data[0].simulacaoRentabilidadeEntities.forEach(simulacao => {
                            let movimento = {
                                dataMovimento: '',
                                valor: 1,
                                imposto: 1,
                                percentualCarregamento: 1,
                                fundoCotacao: []
                            };
                            movimento.dataMovimento = simulacao.anoRentabilidade;
                            movimento.imposto =
                                cobertura.totalFundos *
                                simulacao.demonstrativo.demonstrativo[0].aliquota;
                            movimento.percentualCarregamento =
                                simulacao.valorPercentualCarregamento *
                                (cobertura.totalFundos +
                                    cobertura.totalFundos * simulacao.percentualRentabilidade);
                            movimento.valor =
                                cobertura.totalFundos +
                                cobertura.totalFundos * simulacao.percentualRentabilidade;
                            cobertura.MovimentosProjetados.push(movimento);
                        });
                    })
            )
        );
    });

    forkJoin(all_obs).subscribe(
        undefined,
        undefined,
        () => {
            this.calcularSimulacao();
        }
    );
}

如果您使用的是RxJS 6,请记住导入forkJoin

import { forkJoin } from 'rxjs';

答案 1 :(得分:0)

在RxJS 5中,它看起来像这样。在RxJS 6中,只需将Observable.forkJoin替换为forkJoin

const observables = [];

this.cliente.coberturas.forEach(cobertura => {
  // just create the Observable here but don't subscribe yet
  observables.push(this._dataService.ObterSimulacao(...));
});

Observable.forkJoin(observables)
  .subscribe(results => this.calcularSimulacao());