Problem showing request results http = formbuilder [Angular 6]

0

I am trying to show the results of a query http post in the form through FormBuilder of Angular, the fact is that in .observable() I can print the information, but I can not get it out of that function.

public listado;

  public centro:any = {
      nombre: "nombre",
      telefono: "78945623",
      municipio: "municipio",
      direccion: "direccion"
  }

ngOnInit() {

      //obtenemos datos del centro.
      this.datoscentro();

      // build the form model
      this.myForm = this.fb.group({
      'nombre': [ this.centro.nombre  ,   [Validators.required, Validators.minLength(3)]],
      'telefono': [this.centro.telefono , [ Validators.required ]],
      'municipio': [this.centro.municipio , [ Validators.required ]],
      'direccion': [this.centro.direccion , [ Validators.required ]]
        )
      })
    }

  //obtenemos datos centro
  datoscentro(){
    this.crudProducto.datoscentro(this.id_centro)
    .map((response) => response.json() )
    .subscribe((data) => {
      this.listado = data;
      this.centro.nombre = "este resultado no sale";
      // console.log(this.listado);
    });
  }

Any idea why when centro.nombre assigned a value does not appear in form builder ?

    
asked by Toni 23.07.2018 в 13:57
source

1 answer

0

Because the call to this.crudProducto.datoscentro() is asynchronous and, therefore, you do not have the data until after ngInit() has finished executing. The solution is to fill in the form after to obtain the data:

ngOnInit() {

      //obtenemos datos del centro.
      this.datoscentro();

      // build the form model

    }

  //obtenemos datos centro
  datoscentro(){
    this.crudProducto.datoscentro(this.id_centro)
    .map((response) => response.json() )
    .subscribe((data) => {
      this.listado = data;
      this.centro.nombre = "este resultado no sale";

      //Ahora que tenemos los datos, rellenamos el formulario
      this.populateForm();
    });
  }

populateForm() {
    this.myForm = this.fb.group({
      'nombre': [ this.centro.nombre  ,   [Validators.required, Validators.minLength(3)]],
      'telefono': [this.centro.telefono , [ Validators.required ]],
      'municipio': [this.centro.municipio , [ Validators.required ]],
      'direccion': [this.centro.direccion , [ Validators.required ]]
      });

}
    
answered by 23.07.2018 / 15:49
source