【问题标题】:Undefined Values inside a object对象内的未定义值
【发布时间】:2019-03-20 04:19:59
【问题描述】:

我想用来自服务器的数据填充页面,并能够更改信息,为此我使用 formbuilder 将来自服务器的数据作为默认值使用:

 createForm(){
    this.getGeral()
    this.getTiposTarefas()
    this.formulario = this.fb.group({
      'tipo_tarefa':[this.tarefa.tipoTarefa.id, Validators.compose([Validators.required])], // Cant set default values cuz the array is object is undefined
      'data_tarefa': [this.tarefa.data_tarefa, Validators.compose([Validators.required])],// Cant set default values cuz the array is object is undefined
      'inicio_tarefa': [this.tarefa.inicio, Validators.compose([Validators.required])],// Cant set default values cuz the array is object is undefined
      'fim_tarefa': [this.tarefa.fim, Validators.compose([Validators.required])]// Cant set default values cuz the array is object is undefined
   });
  }

但我没有定义。我在 de subscribe 函数中尝试了 console.log() 并填充了对象“Tarefa”,但不在函数范围内。

    import { Component, OnInit } from '@angular/core';
    import { NavParams, ModalController } from '@ionic/angular';
    import { TarefadetalheService } from './tarefadetalhe.service';
    import { Tarefa } from '../../models/tarefa.model';
    import { TipoTarefa } from '../../models/tipotarefa.model';

    import { FormGroup, FormBuilder, Validators } from '@angular/forms';
    @Component({
      selector: 'app-tarefas-detalhe',
      templateUrl: './tarefas-detalhe.page.html',
      styleUrls: ['./tarefas-detalhe.page.scss'],
    })
    export class TarefasDetalhePage implements OnInit {
     idTarefa = null
     tarefa: Tarefa
     tiposTarefas : TipoTarefa[]
     formulario: FormGroup
      constructor(
        private navParams: NavParams,
        private getTarefaDetalhe: TarefadetalheService,
        private modalController:ModalController,
        public fb: FormBuilder) {   }

      ngOnInit() {

        this.createForm()
      }

      getGeral(){
        this.idTarefa = this.navParams.get('id_tarefa');
        this.getTarefaDetalhe.recuperaDetalhes().subscribe((data: Tarefa)=>{ //passar o id da tarefa como parametro no recupera detalhes
        this.tarefa = data
       })
      }

  getTiposTarefas(){
    this.getTarefaDetalhe.recuperaTiposTarefas().subscribe((data: TipoTarefa[])=>{
    this.tiposTarefas = data
    console.log(this.tiposTarefas) // here it has information
    })
    console.log(this.tiposTarefas) // here it has not information
  }

  createForm(){
    this.getGeral()
    this.getTiposTarefas()
    this.formulario = this.fb.group({
      'tipo_tarefa':[this.tarefa.tipoTarefa.id, Validators.compose([Validators.required])], // Cant set default values cuz the array is object is undefined
      'data_tarefa': [this.tarefa.data_tarefa, Validators.compose([Validators.required])],// Cant set default values cuz the array is object is undefined
      'inicio_tarefa': [this.tarefa.inicio, Validators.compose([Validators.required])],// Cant set default values cuz the array is object is undefined
      'fim_tarefa': [this.tarefa.fim, Validators.compose([Validators.required])]// Cant set default values cuz the array is object is undefined
   });
  }
 closeModal()
 {
   this.modalController.dismiss();
 }
}

当我运行 Ionic 服务时,它会抛出以下错误,我无法在表单控件上设置默认值:

我的 HTML:

<ion-content padding *ngIf="tarefa != null">
  <form [formGroup]="formulario">
    <h4>
      <ion-icon name="list-box"></ion-icon> Geral
    </h4>
    <ion-grid>
      <ion-row>
        <ion-col size="8">
            <ion-label position="floating">Tipo de Tarefa</ion-label>
          <ion-select [formControlName]="tipo_tarefa" okText="Confirmar" cancelText="Cancelar">
            <ion-select-option *ngFor="let tipo of tiposTarefas" [value]="tipo.id">{{tipo.descricao}}</ion-select-option>
          </ion-select>
        </ion-col>
      </ion-row>
    </ion-grid>
    <h4>
      <ion-icon name="calendar"></ion-icon> Horário
    </h4>
    <ion-item-divider></ion-item-divider>
    <ion-grid>
      <ion-row>
        <ion-col size="5">
          <ion-label position="stacked">Data</ion-label>
          <ion-datetime  [formControlName]="data_tarefa" display-format="DD-MM-YYYY" max="2050-10-31" picker-format="DD-MM-YYYY"></ion-datetime>
        </ion-col>
        <ion-col size="3">
          <ion-label position="stacked">Inicio</ion-label>
          <ion-datetime  [formControlName]="inicio_tarefa" display-format="HH:mm" picker-format="HH:mm" ></ion-datetime>
        </ion-col>
        <ion-col size="3">
          <ion-label position="stacked">Fim</ion-label>
          <ion-datetime  [formControlName]="fim_tarefa" display-format="HH:mm" picker-format="HH:mm"></ion-datetime>
        </ion-col>
      </ion-row>
    </ion-grid>
    <h4>
      <ion-icon name="person"></ion-icon> Cliente
    </h4>
    <ion-item-divider></ion-item-divider>
    <ion-grid>
      <ion-row>
      </ion-row>
    </ion-grid>
  </form>
</ion-content>

【问题讨论】:

  • 结论:您必须在订阅回调内部进行处理。在getTiposTarefas 中执行this.formulario = this.fb.group(...) 行(在回调中)。
  • 启动 this.formulario = this.fb.group({ 表单创建仅在您收到之前调用的 2 个函数的所有数据之后。
  • @Manzurul,我该怎么做?抱歉,我是 TS 新手。
  • @TiagoSilveira 发布了答案。

标签: javascript angular typescript ionic-framework ionic4


【解决方案1】:

删除函数getTiposTarefas(),然后进行以下更改。

createForm(){
 this.getGeral();
 this.getTarefaDetalhe.recuperaTiposTarefas().subscribe((data: TipoTarefa[])=>{
 this.tiposTarefas = data;
 this.formulario = this.fb.group({...put the fields...});
  console.log(this.tiposTarefas) // here it has information
 })
}

更新: 您需要先初始化这个tarefa: Tarefa 对象。见下文

tarefa: Tarefa =  {
  comentarios: '',
  data_tarefa: '',
  descricao: '',
  fim: '',
  id_aprovador: '',
  id_cliente: '',
  id_criador: '',
  id_sala: '',
  id_sistema: '',
  id_solicitante: '',
  inicio: '',
  nome_aprovador: '',
  nome_cliente: '',
  nome_criador: '',
  nome_sistema: '',
  nome_solicitante: '',
  numero: 0,
  participante: [],
  status_tarefa: 0,
  tarefa: '',
  tipoTarefa: {
      id:'',
      interna: null,
      descricao: ''
  }
};

那么它应该可以正常工作。

【讨论】:

  • 它可以工作,但代码有点混乱哈哈,所以......现在它抛出其他错误是:formGroup 需要一个 FormGroup 实例。请传一个。
  • 这可能在你的视图文件中你需要放
  • 使用 HTML 编辑
  • 如果你有相同的 formGroup 并且仍然出现错误,那么问题出在其他地方,需要查看 plunker。
  • 这是我的仓库,我不知道它是否有帮助,但是.. github.com/tiagosilveiraa/PManager
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多