ngOnInit does not save value of the variable returned by a function

Asked

Viewed 119 times

1

I have the following function:

 getCampos(id: String) {
console.log('id em getCampos:', id);
this.es.getDocument(EditSiteComponent.INDEX, EditSiteComponent.TYPE, id).then(
  response => {
    this.campos = response[0]._source;
    console.log('Campos em getCampos',this.campos);
    return this.campos;
  }, error => {
    console.log('Erro', error);
  });

}

I’m sure the same works, because the console.log present the expected value.

Now when I take her value in ngOnInit:

ngOnInit() {
    console.log('Edit site component ----------');
    this.fields = this.getCampos(this._id);
     console.log(this.fields);
  }

The value of fields becomes as undefined for some reason. The idea is to take this object and access its attributes in an angular form.

2 answers

1


This is because Javascript, Typescript in this case eh asynchronous. Then in the function below:

ngOnInit() {
  console.log('Edit site component ----------');
  this.fields = this.getCampos(this._id);
  console.log(this.fields);
}

All lines are processed in sequence, the third line, console.log(this.fields) is executed before the value of this.fields is ready to be displayed.

You need to structure your code so that you ensure that a certain value is only called after it is loaded.

Note this happening in the other function, in the section below:

this.es.getDocument(EditSiteComponent.INDEX, EditSiteComponent.TYPE, id).then(
  response => {
    this.campos = response[0]._source;
    console.log('Campos em getCampos',this.campos);
    return this.campos;
  }, error => {
    console.log('Erro', error);
  });

The then, calls a function of callback only when its function this.es.getDocument is completed, here is a call synchronized. That’s why you have the values printed correctly.

0

I use formBuilder to take the values and work on a form.

import { Component, OnInit, ElementRef } from '@angular/core';
import { ActivatedRoute, Router } from "@angular/router";
import { FormBuilder, FormGroup, Validators } from "@angular/forms";
import { Location } from '@angular/common';
import { switchMap } from 'rxjs/operators';

import { Formularios } from '../../../interface/formularios';
import { FormulariosService } from '../../../services/formularios.service';
import { Modulos } from '../../../interface/modulos';
import { ModulosService } from '../../../services/modulos.service';

@Component({
  selector: 'app-modulos-shortcut',
  templateUrl: './modulos-shortcut.component.html',
  styleUrls: ['./modulos-shortcut.component.css']
})
export class ModulosShortcutComponent implements OnInit {

  modulos: Modulos[];
  modulo: Modulos;
  formularios: Formularios;
  formulariosForm: FormGroup;
  currentAction: string;
  pageTitle: string;
  idModulo: any;

  constructor(private formulariosService: FormulariosService,
              private router: Router,
              private route: ActivatedRoute,
              private formBuilder: FormBuilder,
              private modulosService: ModulosService,
              private elementRef: ElementRef,
              private location: Location) { }

  ngOnInit() {
    this.setCurrentAction();

    this.formulariosForm = this.formBuilder.group({
      id_formulario: [null],
      nome_formulario: [null, Validators.required],
      descricao: [null, Validators.required],
      id_modulo: [null, Validators.required],
      url: [null, Validators.required]
    });

    this.getListModulos();
    this.loadPage();
  }
  private setCurrentAction() {

    this.currentAction = 'new';
    this.pageTitle = 'Criar Formulario';

  }

  private loadPage() {
    this.idModulo = this.route.snapshot.params.id;
    this.modulosService.getId(this.idModulo).subscribe(
      (modulo: Modulos) => {this.updateForm(modulo); }
    );
  }

  private updateForm(item) {
    console.log(item[0]);
    this.formulariosForm.patchValue({
      id_modulo: item[0].id_modulo
    });
  }

  onSubmit() {

    if(this.formulariosForm.valid) {
      this.formulariosService.create(this.formulariosForm.value).subscribe(
        (response) => {console.log(response); this.router.navigate(['modulos']);},
        (error) => {console.log(error); }
      );
    } else {
      this.validatedForm(this.formulariosForm);
    }
  }

  validatedForm(formGroup: FormGroup) {
    Object.keys(formGroup.controls).forEach(
      campo => {console.log(campo);
      const controle = formGroup.get(campo);
      controle.markAsTouched(); }
      );
  }

  goBack() {
    this.location.back();
  }

  getListModulos() {
    this.modulosService.getList().subscribe(
      (modulos: Modulos[]) => {this.modulos = modulos; }
    );
  }
}

In html it looks like this:

<a (click)="goBack()" class="btn btn-warning btn-md m-3">
  <span class="glyphicon glyphicon-backward"></span> &lt;&lt; Voltar
</a>
<div class="m-5">
    <h3>{{ pageTitle }} </h3>

</div>
<form class="m-5" [formGroup]="formulariosForm" (submit)="onSubmit()">
  <div class="form-row">
    <div class="form-group col-md-5">
      <label for="nome_formulario">Nome do Formulário</label>
      <input type="text" class="form-control" id="nome_formulario" formControlName="nome_formulario">
      <div class="small" *ngIf="!formulariosForm.controls['nome_formulario'].valid && formulariosForm.controls['nome_formulario'].touched"> Nome do Formulário não pode ficar em branco!</div>
    </div>
  </div>

  <div class="form-row">
    <div class="form-group col-md-5">
      <label for="descricao">Descrição</label>
      <input type="text" class="form-control" id="descricao" formControlName="descricao">
      <div class="small" *ngIf="!formulariosForm.controls['descricao'].valid && formulariosForm.controls['descricao'].touched"> A Descrição não pode ficar em branco!</div>
    </div>
  </div>

  <div class="form-row">
    <div class="form-group col-md-5">
      <label for="id_modulo">ID Módulo</label>
      <select name="modulo" id="modulo" class="form-control modulo" formControlName="id_modulo" [attr.disabled]="true">
        <option value="{{ m.id_modulo }}" *ngFor="let m of modulos" >{{m.nome_modulo }}</option>
      </select>
    </div>
  </div>

  <div class="form-row">
    <div class="form-group col-md-5">
      <label for="url">URL</label>
      <input type="text" class="form-control" id="url" formControlName="url">
      <div class="small" *ngIf="!formulariosForm.controls['url'].valid && formulariosForm.controls['url'].touched"> A URL não pode ficar em branco!</div>
    </div>
  </div>

  <div class="form-row">
    <div class="form-group col-md-12">
        <button [disabled]="!formulariosForm.valid" type="submit" class="btn btn-success btn-lg float-right mt-3 mb-4">Salvar</button>
    </div>
  </div>

</form>

Browser other questions tagged

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