Unable to retrieve data following a promise in Ionic 3

Hello, I'm currently working on an Ionic application that needs to display data in a Form Group after retrieving it with a SOAP ReadData request.

Although I call my function and try to display the data in the form, there seems to be an issue as the form is not appearing.


constructor(
  public navCtrl: NavController,
  public navParams: NavParams,
  private privacyProvider: PrivacyProvider,
  private formBuilder: FormBuilder
) {
  
  this.myParam = navParams.get('myParam');

  console.log(this.myParam);

  this.getData().then(() => {
    console.log(this.iobData);
    debugger;
    this.formData = this.formBuilder.group({
      ID_INSTALLATO: new FormControl(this.iobData.id_installato),
      ID_ANAGRAFICA: new FormControl(this.iobData.id_anag),
      ID_PRODUTTORE: new FormControl(this.iobData.id_produttore),
      ID_GRUPPO: new FormControl(this.iobData.id_gruppo),
      ID_INSTALLATORE: new FormControl(this.iobData.id_installatore)
    });
  });

}

getData(){
  return new Promise((resolve, reject) =>{
    this.privacyProvider.getIOBData(this.myParam).subscribe((data)=>{
      if (data) {
        this.iobData = data;
        resolve(true);
      } else {
        reject();
      }
    })
  });
}

How can I resolve this issue? Here is my HTML code:


<ion-content>
  <ion-list *ngIf="formLoaded">
    <form [formGroup]="formData">
      <ion-item>
        <ion-label stacked>ID INSTALLATO</ion-label>
        <ion-input formControlName="ID_INSTALLATO" type="text"></ion-input>
      </ion-item>
      <ion-item>
        <ion-label stacked>ID ANAGRAFICA</ion-label>
        <ion-input formControlName="ID_ANAGRAFICA" type="text"></ion-input>
      </ion-item>
      <ion-item>
        <ion-label stacked>ID PRODUTTORE</ion-label>
        <ion-input formControlName="ID_PRODUTTORE" type="text"></ion-input>
      </ion-item>
      <ion-item>
        <ion-label stacked>ID GRUPPO</ion-label>
        <ion-input formControlName="ID_GRUPPO" type="text"></ion-input>
      </ion-item>
      <ion-item>
        <ion-label stacked>ID INSTALLATORE</ion-label>
        <ion-input formControlName="ID_INSTALLATORE" type="text"></ion-input>
      </ion-item>
    </form>
  </ion-list>

Answer №1

Make sure to always remember to set your formLoaded flag as true.

You can implement it like this:

this.getAnagrafica().then(() => {
    console.log(this.iobAnagrafica);
    debugger;
    this.formAnagrafica = this.formBuilder.group({
      ID_INSTALLATO: new 
 FormControl(this.iobAnagrafica.id_installato),
      ID_ANAGRAFICA: new FormControl(this.iobAnagrafica.id_anag),
      ID_PRODUTTORE: new 
 FormControl(this.iobAnagrafica.id_produttore),
      ID_GRUPPO: new FormControl(this.iobAnagrafica.id_gruppo),
      ID_INSTALLATORE: new 
 FormControl(this.iobAnagrafica.id_installatore)
      });

      this.formLoaded = true;
   });

Answer №2

I suggest utilizing ngModel in your specific scenario: https://ionicframework.com/docs/developer-resources/forms/ set up a variable in your typescript file

public callBack;
constructor(
  public navCtrl: NavController,
  public navParams: NavParams,
  private privacyProvider: PrivacyProvider,
  private formBuilder: FormBuilder
  ) {

  this.myParam = navParams.get('myParam');

  console.log(this.myParam);

  this.getAnagrafica().then((chart) => {
    this.callBack = chart;
 }
...

once done, the data should populate the fields and you can also utilize the callBack variable for ngIf conditionals

<ion-content>
<ion-list *ngIf="callBack">
<form [formGroup]="formAnagrafica">
  <ion-item>
    <ion-label stacked>ID INSTALLATO</ion-label>
    <ion-input [(ngModel)]="callBack.id_installato" formControlName="ID_ANAGRAFICA" type="text"></ion-input>
  </ion-item>
...

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

Navigating session discrepancies: Combining various social media platforms using Next.js and NextAuth

Recently, I ran into a problem where, upon logging in with Google, I found myself needing access tokens for Twitter and LinkedIn to send out API requests. The issue came about when NextAuth modified my session data to be from either Twitter or LinkedIn ins ...

Guide on specifying the return type of a generic class when using TypeScript

The code I am working with is structured like this: import * as events from 'events' // Utilizing Node.js events module // My custom implementation of EventEmitter with enhanced typing interface IEventEmitter<EventTypes> { /* ... */ } // ...

The issue in Angular2 viewmodel where the boolean value fails to update the *ngIf template

I'm seeking assistance with an unusual issue in my Angular2 and Typescript application. Within my template, I have the following HTML utilizing ngIf: <div *ngIf="loading" class="row"> <div class="small-3 small-centered columns" > ...

How can Angular prevent displaying 404 errors in the console by utilizing fallback mechanisms?

I have implemented a custom directive that loads a backup image source if the initial one returns a 404 error. Here is the code for the directive: .directive('errSrc', function() { return { link: function(scope, element, attrs) { ...

Combining numerous interfaces into a unified interface in Typescript

I'm struggling to comprehend interfaces in Typescript, as I am facing difficulty in getting them to function according to my requirements. interface RequestData { [key: string]: number | string | File; } function makeRequest(data: RequestData) { ...

Identifying Angular 2 templates post-file separation: a step-by-step guide

I am currently trying to figure out how to initiate a project in Angular 2 and have encountered an issue. Following the steps outlined in this Angular 2 guide, I was able to separate my .ts files from .js files by configuring my 'temp' directory ...

Using the useRef hook to target a particular input element for focus among a group of multiple inputs

I'm currently working with React and facing an issue where the child components lose focus on input fields every time they are re-rendered within the parent component. I update some state when the input is changed, but the focus is lost in the process ...

Selecting logic depending on the request body in NestJS

Currently, my controller looks like the following: @Controller("workflow") export class TaskWorkflowController { public constructor( private readonly jobApplicationActivityWorkflow: JobApplicationActivityService ) {} @Post("/:job- ...

What is the appropriate return type for this function in TypeScript?

Seeking clarity on a fundamental TypeScript concept here. I've noticed that Google Cloud examples use JavaScript, and I'm in the process of converting one to TypeScript. Source: https://cloud.google.com/storage/docs/listing-buckets#storage-list ...

Struggling with making updates to an interface through declaration merging

I am encountering challenges with implementing declaration merging on an interface from a library that I created. An example illustrating the issue using StackBlitz can be viewed here: https://stackblitz.com/edit/typescript-qxvrte (issues persist in both ...

What is the best way to implement an Angular Guard that utilizes an API service for validation and redirects in case of failure?

Hello there! I am currently working on an Angular 7 application that deals with time cards. One of the main features I have implemented is a CanActivate Guard for controlling access to certain components. The CanActivate code utilizes Observables to decid ...

Having difficulties generating ngc and tsc AOT ES5 compatible code

I've explored various options before seeking help here. I have an angular2 library that has been AOT compiled using ngc. Currently, I am not using webpack and solely relying on plain npm scripts. Below is the tsconfig file being utilized: { "comp ...

Cordova's FileReader takes precedence over TypeScript's FileReader functionality

I encountered an issue when adding the cordova-plugin-file-transfer plugin, where I received the error message: reader.addEventListener is not a function. This problem arises due to Cordova FileReader class overriding typescript FileReader. How can this ...

Exploring the possibilities of ZMQ_XPUB_MANUAL in action with zeromq.js

I'm currently in the process of setting up a pub/sub broker using ZeroMQ, and I want to ensure that clients are only able to subscribe to authorized prefixes. While researching this topic, I came across a helpful tutorial that discusses achieving a si ...

Tips for converting a string array constant into a union type

I have a string array that I want to use to create a new type where the properties correspond to the elements in the array. There are different types of arrays and I have a function that generates different output types based on the input array. const RG ...

Utilizing the power of dojo/text! directly within a TypeScript class

I have encountered examples suggesting the possibility of achieving this, but my attempts have been unsuccessful. Working with Typescript 2.7.2 in our project where numerous extensions of dijit._Widget and dijit._TemplatedMixin are written in JavaScript, w ...

You cannot assign type 'Node | null' to type 'Node' when attempting to loop through HTML elements in TypeScript

In my code, I am taking a raw Markdown string stored in 'markdownString' and using the marked.js library to convert it to HTML for display on a web browser. My goal is to extract all plain text values from the page and store them in an array of s ...

What is the best method to locate an element<T> within an Array[T] when <T> is an enum?

I've recently started learning TypeScript and exploring its functionalities. I could use some assistance in deepening my understanding. Within our angular2 application, we have defined an enum for privileges as follows: export enum UserPrivileges{ ...

When comparing TypeScript index signatures to Record<Keys, Type> return type, the focus is on handling objects with unspecified properties

I have a function called getQueryParams that takes a string as input and returns an object with unknown properties: function getQueryParams(s) { if (!s || typeof s !== 'string' || s.length < 2) { return {} } return s .substr(1) ...

Discovering the import path of Node modules in ReactAlgorithm for determining the import path of

Software Development In my current project, I am utilizing Typescript along with React. To enhance the application, I integrated react-bootstrap-date-picker by executing yarn install react-bootstrap-date-picker. Unfortunately, there is no clear instruct ...