Unspecified data stored within an object

I am looking to populate a page with data from the server and have the ability to update the information. To achieve this, I am using formbuilder to fetch data from the server as the default value. Here's how I am implementing it:

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

However, the values are coming up as undefined. I inserted console.log() inside the subscribe function and confirmed that the object 'Tarefa' is populated, but it is not outside the function scope.

 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)=>{ //pass the task id as a parameter in the recovery details
        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])], // Unable to set default values because the array object is undefined
      'data_tarefa': [this.tarefa.data_tarefa, Validators.compose([Validators.required])],// Unable to set default values because the array object is undefined
      'inicio_tarefa': [this.tarefa.inicio, Validators.compose([Validators.required])],// Unable to set default values because the array object is undefined
      'fim_tarefa': [this.tarefa.fim, Validators.compose([Validators.required])]// Unable to set default values because the array object is undefined
   });
  }
 closeModal()
 {
   this.modalController.dismiss();
 }
}

After running Ionic serve, I encountered the following error, preventing me from setting default values on the form controls:

https://i.sstatic.net/h4tTu.png

Here is the HTML code:

<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>

Answer №1

Start by removing the function getTiposTarefas() and following these instructions:

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
 })
}

Update: Make sure to initialize the tarefa: Tarefa object first. Here is how:

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: ''
  }
};

Once done, everything should work smoothly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Calculate the length of a JSON array by using the value of one of its

What is the most efficient way to obtain the length of a JSON array in jQuery, based on the value of its attribute? As an illustration, consider the following array: var arr = [{ "name":"amit", "online":true },{ "name":"rohit", "online":f ...

Creating an Editor for Input Text Field in HTML: A Step-by-Step Guide

In the vast landscape of JS libraries that can achieve this function, like Trumbowyg and more. However, prior to my rails project displaying that slim version, I need to ensure JavaScript is properly escaped! Therefore, I need to create an editor using o ...

Encountering SUID Sandbox Helper Issue When Running "npm start" on WSL with Electron and Typescript

Can anyone help me with this issue? I have Node v8.10.0 and I'm attempting to follow a beginner tutorial on Electron + Typescript which can be found at the following link: https://github.com/electron/electron-quick-start-typescript Here is the full e ...

Converting JSON to a list using JavaScript

As a beginner in JavaScript, I apologize for asking possibly a redundant question. Can someone guide me on the most effective way to parse json? I am specifically interested in extracting a list of strings under the name Maktg: { "d":{ "res ...

What could be causing my JavaScript loop to replace existing entries in my object?

Recently, I encountered an issue with an object being used in nodejs. Here is a snippet of the code: for(var i = 0; i < x.length; i++) { var sUser = x[i]; mUsers[sUser.userid] = CreateUser(sUser); ++mUsers.length; ...

How can I ensure that the height of my dropdown menu covers the entire screen without being limited by the page height

I'm trying to adjust a dropdown menu so that it fits perfectly within the screen size, covering the entire height without showing any content beneath or below it. Currently, the menu covers the screen on some pages but scrolls and appears too large du ...

Pass a JavaScript variable to a PHP script using AJAX when a button is clicked, with a dynamically set href attribute

This is the current situation: There is a checkbox on each row of a table that represents some information An initially disabled button becomes enabled when any checkbox is checked The button is enclosed by an <a></a> tag as shown: <a>&l ...

React did not allow the duplicate image to be uploaded again

I've implemented a piece of code allowing users to upload images to the react-easy-crop package. There's also an "x" button that enables them to remove the image and upload another one. However, I'm currently facing an issue where users are ...

Creating Knockout Markup within MVC 3

We're in the process of developing a new infrastructure for our MVC client to minimize the need for extensive Javascript coding, especially since most of our developers are primarily working on desktop applications. One approach I've taken for o ...

Error: User cannot be used as a constructor

When attempting to register a user using a Node.js app and MongoDB, I encountered the following error message: const utente = new Utente({ ||||| TypeError: Utente is not a constructor This is my model file, utente.js: const mongoose = require("mongoose") ...

What sets Angular Material apart from AngularJS Material when it comes to responsiveness?

I am facing a dilemma in choosing a framework for my application. In my search, I came across Angular Material and AngularJS Material. Although both frameworks are developed by Google (correct me if I'm wrong), they seem to serve the same purpose of r ...

The curly braces in AngularJS are failing to display the values on the HTML page

After trying various articles and solutions to different questions, I am still unable to resolve my issue. I am working on a blank ionic project and it is running smoothly in my browser using ionic serve without any errors. However, instead of displaying ...

Various behaviors in multiple instances of DatePicker

Currently, I have a form with two datePicker elements (using jQuery UI). When I hover over a date in the first datePicker, an AJAX call is made successfully. However, the issue is that the AJAX call is triggered for both datePickers when I only want it to ...

Display a table using Angular's md-card and md-color

Hey there! I'm currently working on printing a table that is filled with data in an md-card. The background color is set using the md-color theme picker, which you can check out here. However, I'm encountering an issue where the printed table onl ...

Cheerio's method of extracting data from an HTML table using web scraping

Currently, I am facing an issue with a web scraping project. The specific webpage that I am attempting to scrape looks something like this: <table style="position..."> <thead>..</thead> <tbody id="leaderboard_body"> ...

Disable the outer div scrolling in VueJS, but re-enable it once the inner div has reached the bottom of

I am currently working on a webpage that contains multiple divs stacked vertically. Here is the concept I am working with: Once the scrollbar reaches the bottom of the first div, the outer scrollbar will be disabled and the inner scrollbar will be enabled ...

How to Implement Autocomplete Feature in Angular

CSS <div class="dropdown"> <input type="text" formControlName="itemName" (ngModelChange)="filterItems()" class="dropdown-input" (keyup)="onKeyPress($event)" (blur)="toggleDropdown(0)" (focus)="toggleDropdown(1)" placeholder="Search..." [ngCla ...

Guide on utilizing Angular CDK Drag and Drop library for uploading files

I've been working on a unique angular file-upload component and wanted to integrate Angular CDK drag&drop for an enhanced user experience. Unfortunately, when attempting to use it for file uploads (dragging files into the dropzone), I encountered ...

Iterate over the table data and present it in the form of a Google

I'm struggling to extract data from a table and display it in a google chart. I need some guidance on how to properly loop through the information. HTML <tr> <th>Date</th> <th>Score</th> <th>Result< ...

When a form contains a ViewChild element, changes to the ViewChild element do not automatically mark the

Let's set the stage: MainComponent.html <form #someForm > <input type="text" name="title" [(ngModel)]="mainVar" /> <child-component /> <input type="submit" [disabled]="someForm.form.pristine" /> </form> ChildComp ...