How to call a method when using the switchMap operator

Asked

Viewed 101 times

0

I’m studying reactive forms, working with Framework Angular.

Thinking about functional and reactive programming, I’m listening to the status changes of the control cep, then, first I used the operator distinctUntilChanged where it will only issue when the value is changed, that is, we will have an event issued when typing the first number as INVALID, because I put a validation via regex where it is necessary to have at least 8 digits, then when typed the eighth number will be issued an event with the status VALID

this.formulario.get('endereco.cep').statusChanges
  .pipe(
    distinctUntilChanged(),
    switchMap(status => status === 'VALID' ?
      this.cepService.consultaCEP(this.formulario.get('endereco.cep').value)
      : empty())
  )
  .subscribe(dados => dados ? this.populaEnderecoForm(dados) : {});

So I used the operator switchMap, so that only the subscribe if the control status cep be it VALID and be returned from the method consultaCEP one Observable.

The code is functional, however, I need to call the method below, even if, the control status cep be it INVALID.

resetaEnderecoFormulario() {
  this.formulario.patchValue({
  endereco: {
    complemento: null,
    rua: null,
    bairro: null,
    cidade: null,
    uf: null
  }
});

}

I could do it in other ways, but I would like an idea taking into account functional and reactive programming.

1 answer

0


To be able to call the method resetaEnderecoFormulario(), I made the following change:

this.formulario.get('endereco.cep').statusChanges .pipe( distinctUntilChanged(), switchMap(status => { this.resetaEnderecoFormulario(); return status === 'VALID' ? this.cepService.consultaCEP(this.formulario.get('endereco.cep').value) : empty() }) ) .subscribe(dados => dados ? this.populaEnderecoForm(dados) : {});

I mean, I put the logic of switchMap, in keys {}, and defined the return as the result of the function if

Browser other questions tagged

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