0

maybe someone can improve it using RxJs operators, but i have no idea, because i need the value of the first request:

adicionarUnidade() {

this.restApi.createUnidade(this.unidadeDetalhes).subscribe((res: Unidade) => {

  this.unidadeResponseArr = res;
  this.unidadeUsuarioDetalhes.unidadeId = this.unidadeResponseArr.data.id;

  for (let i = 0; i < this.unidadeUsuarioArr.length; i++) {
    this.unidadeUsuarioDetalhes.usuarioId = this.unidadeUsuarioArr[i].id;

    this.restApi.createUnidadeUsuario(this.unidadeUsuarioDetalhes).subscribe(() => {

     this.router.navigate(['/unidade/lista-de-unidades']);
    });
  }
});

}

  • What is this doing? Create unit, loop, create user and navigate inside the loop? – SGalea Aug 14 '19 at 12:59
  • first it's create the unity, then with the value of the unity to add the users to that unity – Rodrigo Spinelli Aug 14 '19 at 13:02
  • yes but why the navigate inside the loop? and can you modify the back-end? One request with a set of Ids and add them all – SGalea Aug 14 '19 at 13:04
  • 1
    I am surprised this is working for you currently. The navigate not being run before you have finished looping over the array... Must be a very small array? If you want to send multiple requests in parallel you should take a look at the mergeMap operator in RXJS library, you can create multiple observables and merge them into one to send at once, then subscribe to the completion of call before navigating. – Sam Aug 14 '19 at 13:07
  • @Sam It can't work. Such nested subscriptions doesn't work – Florian Aug 14 '19 at 13:10
  • You shouldn't use nested subscribes. Check out operators like mergeMap, switchMap, combine etc on how to do it correctly. – Shumail Aug 14 '19 at 13:11
  • Possible duplicate of [Angular Subscribe within Subscribe](https://stackoverflow.com/questions/55447803/angular-subscribe-within-subscribe) – wentjun Aug 14 '19 at 13:14
  • for your surprise its working perfectly but i know that there's some operators who i can use to improve it – Rodrigo Spinelli Aug 14 '19 at 13:14

0 Answers0