Angular 7 waiting service reply to continue

Asked

Viewed 233 times

0

Good afternoon, guys, I have two methods, how do I wait for a method that is calling an external service to respond to continue the execution of the method that called this method? Example:

salvarUsuario(){
this.usuario = formUsuario.value();
this.pegarEndereco(this.usuario.cep);
this.usuarioService.salvar().subscribe();
}

pegarEndereco(cep: string){
this.cepService.buscarPorCep(cep).subscribe((response: any) => {
this.usuario.endereco = response;
});
}

In that case, I just want to continue the execution after the takeAddress() reply.

Note: I didn’t want to make the call inside the cepService subscribe.search)

  • you have to create an observable, from a read: https://angular.io/guide/observables

  • Have to do inside the subscribe pq is asynchronous

1 answer

2

You can "subscribe" to the "get Address" function inside the Save.

salvarUsuario(){
  this.usuario = formUsuario.value();
  this.pegarEndereco(this.usuario.cep).subscribe(success -> {
         this.usuarioService.salvar().subscribe();
  }, error -> {
         fazerAlgumaCoisa();
  });

}

pegarEndereco: any(cep: string){
  return this.cepService.buscarPorCep(cep);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.