ожидание наблюдаемой подписки внутри foreach до конца - PullRequest
0 голосов
/ 06 июня 2018

Я перебираю массив объектов, и для каждой итерации я запускаю 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();

  }

мне нужно вызвать calcularSimulacao () после того, как все подписки внутри coberturas.foreach завершены.Любые советы?

Ответы [ 2 ]

0 голосов
/ 06 июня 2018

Вы можете попробовать использовать forkJoin с onCompleted обратным вызовом.См. Ниже:

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();
        }
    );
}

Просто не забудьте импортировать forkJoin, если вы используете RxJS 6.

import { forkJoin } from 'rxjs';
0 голосов
/ 06 июня 2018

В 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());
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...