Showing json information in input area using Angular 10

I'm facing an issue with editing a form after pulling data from an API. The values I retrieve are all null, leading to undefined errors. What could be the problem here?

Here's what I've tried so far:

   async ngOnInit(): Promise<void> {
        this._activatedroute.paramMap.subscribe(params => {
          this.id = params.get('id');
        });
        let user = this.service.getUserSession();
        if (user != null) {
          this.project = user.currentProject.id;
        }
        this.userSession = this.userSessionService.getSession("usersession");
        this.projectId = this.userSession.currentProject.id;
        this.totalTeamsData = await this.teamService.getTeamList(this.projectId);
        await this.getTicketData();
      }
    
      async getTicketData(): Promise<void> {
          this.ticketData = await this.ticketService.getTicket(this.id, this.projectId);
          await this.toggleTicketDetails();
        
      }
    
      toggleTicketDetails() {
        console.log("the dats is", this.ticketData); //this shows the data from the api with all the fields
console.log("the dats is", this.ticketData.title); //this shows undefined 

        this.title = this.ticketData.title;
        this.description = this.ticketData.description;
        this.teamId = this.ticketData.teamId;
        this.totalTeamsData.forEach(async (data: string) => {
          if (data === this.teamId) {
            this.totalTeamMembersData = await this.teamService.getTeamMembers(this.projectId, this.teamId);
            this.totalEAData = await this.teamService.getTeamEAList(this.projectId, this.teamId);
          }
        });
        this.assignedTo = this.ticketData.assignedTo;
        this.eaId = this.ticketData.eaId;
        this.countryId = this.ticketData.countryId;
        this.projectId = this.ticketData.projectID;
        this.country = this.ticketData.country;
        this.priority = this.ticketData.priority;
        this.category = this.ticketData.category;
        this.status = this.ticketData.status;
        this.lab = this.ticketData.lab;
        this.impact = this.ticketData.impact;
        this.content = this.ticketData.content;
        this.resolution = this.ticketData.resolution;
      }

When I log

console.log("the dats is", this.ticketData);
, I can see the JSON data as follows:

[    
   {
      "id": "4e600c3d-efed-43c2-b395-6238510dda24",
      "title": "Test",
      "assignedTo": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5226372126372012353f333b3e7c313d3f">[email protected]</a>",
      "description": "Test",
      "resolution": null,
      "country": "USA",
      "projectID": "ABC",
      "teamId": "901",
      "eaId": "901",
      "countryId": "0001",
      "priority": "Urgent",
      "status": "Open",
      "lab": null,
      "category": "Duplicate",
      "content": null,
      "impact": null,
      "dateCreated": 1619313188806,
      "createdBy": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1f6b7a6c6b7a6d5f78727e7673317c7072">[email protected]</a>"
    }
]

This is a snippet of the console log.

Why am I getting 'undefined' for

this.title = this.ticketData.title;
and other properties?

The HTML sample:

<div class="row">
                        <div class="col-md-12">
                            <div class="form-group">
                                <label for="title" style="color: black;">Title<span style="color: red;">*</span></label>
                                <input type="text" class="form-control" style="color: black;"
                                    required id="title" name="title" [(ngModel)]="title">
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-12">
                            <div class="form-group">
                                <label for="description" style="color: black;">Description<span style="color: red;">*</span></label>
                                <textarea type="text" class="form-control" rows="3" style="color: black;"
                                    required id="description" name="description" [(ngModel)]="description">
                                </textarea>
                            </div>
                        </div>
                    </div>

Answer №1

When your endpoint returns an array of objects instead of a single object, you can easily identify this in the console log. The log will begin with "[" indicating the data is an array.

To fix this issue, simply access the first element of the array and assign it to the ticket data like so:

this.ticketData = (await this.ticketService.getTicket(this.id, this.projectId))[0];

If you want to provide a better user experience, you can check for an empty response array before proceeding:

let dump = await this.ticketService.getTicket(this.id, this.projectId);
if(!dump && dump.length==0)
{
    //Notify the user that the data is empty
}
else {
    this.ticketData = await this.ticketService.getTicket(this.id, this.projectId);
    await this.toggleTicketDetails();

}

Answer №2

Here is a recommended way to handle this situation

.....

data: any;
parsedData: any;
label: string;

.....

// Parsing the data from JSON format
this.parsedData = JSON.parse(this.data);
this.label = this.parsedData.title   

Modified Version

Since the console log displays an array, you should access the array object property in the following manner:

this.data[0].title

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

Implementing dynamic image insertion on click using a knockout observable

I'm utilizing an API to retrieve images, and I need it to initially load 10 images. When a button is clicked, it should add another 10 images. This is how I set it up: Defining the observable for the image amount: public imageAmount: KnockoutObserva ...

Transform JSON into an Array and generate a new Array from a collection of Arrays

I'm struggling with generating a table in Angular2 from JSON data because I need to pivot the information, but my usual method doesn't seem to work for this scenario. Below is an excerpt of the JSON data I am working with: [ { "ValueDate" ...

The @Input decorator in Angular 2/4 is designed to only transfer fundamental values and not collections or complex data

I have encountered an issue while attempting to use @Input with a list of objects, where the @Input variable ends up being undefined. What is functioning properly can be seen in home.component.html: <p> <it-easy [mycount]="countItem" (result ...

What is the correct way to implement "next-redux-wrapper" with "Next.js", "Redux-ToolKit" and Typescript?

Currently, I am integrating RTK (redux-toolkit) into my Next.js App. I am facing an issue while trying to dispatch an AsyncThunk Action within "getInitialProps". During my research, I came across a package named "next-redux-wrapper" that allows access to t ...

Guide for setting up filtering and sorting on a multi-value array column with MUI's data grid

I've encountered an issue with the MUI Data Grid component's free version, specifically regarding filtering and sorting on a column that displays multiple values in an array. The problematic column in this case is 'tags', which showcase ...

Error encountered while attempting to generate migration in TypeORM entity

In my project, I have a simple entity named Picture.ts which contains the following: const { Entity, PrimaryGeneratedColumn, Column } = require("typeorm"); @Entity() export class Picture { @PrimaryGeneratedColumn() ...

Click on the button to open the generated link in a new tab

How can I efficiently open a URL in a new tab after making an API call with the click of a button? Currently, the button triggers the API call and generates the URL. <button (click)="getUrl()">Connect</button> In TypeScript: getUrl() ...

Utilize TypeScript to import a JSON file

I am trying to incorporate a JSON file using TypeScript, which contains data about different regions in Italy along with their respective capitals. Here is a snippet of the data: { "italia": [ { "regione": "Abruzzo", "capoluoghi": [ ...

Leverage the power of forkJoin alongside activatedRoute

One of the observables I'm working with is the following: formData$ = forkJoin([ this.httpService.getProgramsLevelsList(), this.httpService.getProgramsTypesList(), this.httpService.getQuestionnaireReasonsList() ]).pipe( tap((res: any) => ...

Encountering the "DevToolsActivePort file does not exist" error when executing Angular e2e tests via GitHub Actions

Currently delving into the world of GitHub actions, I am in the process of executing Angular e2e tests within a continuous integration workflow. Utilizing the basic project structure generated by the Angular CLI, I have primarily focused on adjusting the ...

The attribute 'y' is not found within the data type 'number'

Currently working on a project using Vue.js, Quasar, and TypeScript. However, encountering errors that state the following: Property 'y' does not exist on type 'number | { x: number[]; y: number[]; }'. Property 'y' does not ...

How come the information I receive when I subscribe always seems to mysteriously disappear afterwards?

I've been working on a web project using Angular, and I've run into an issue with my code that's been causing problems for a while now. The problem lies in fetching data from a server that contains translations: getTranslations(): Observab ...

Testing onClick using Jest when it is not a callback function in props

I have discovered various ways to utilize mock functions in jest for spying on callback functions passed down to a component, but I have not found any information on testing a simple onClick function defined within the same component. Here is an example f ...

Angular - Ensuring service completion before proceeding with navigation

I'm currently facing an issue where I need to populate data in a service before navigating, but the navigation is happening before the data is ready. Here's the code in my service: addToken(token) { this.cookieService.set( 'token', ...

Let's compare the usage of JavaScript's toUTCString() method with the concept of UTC date

When I fetch the expiry date time in UTC from the Authentication API along with a token, I use the npm jwt-decode package to extract the information. private setToken(value: string) { this._token = value; var decoded = jwt_decode(value); this._ ...

Incorporate any enum value into a Typescript interface

I'm working with a Typescript interface export interface MyInterface { valid: boolean; resourceType: MyEnum; message: string; } As well as an enum enum MyEnum { 'a', 'b', 'c' } Is there a way to allow the ...

"Techniques for incorporating a screen in Angular application (Switching between Edit and View modes) upon user interaction

We are currently working on a screen that requires the following development: This screen will have the following features: When clicking on a button, the fields should become editable. In the image provided, there is some repeated data, but in our case, ...

WebStorm disregards tsconfig compiler directives when working with Angular applications

My project structure was created using angular-cli, which includes a root tsconfig.json, src/tsconfig.app.json, and src/tsconfig.spec.json. Despite having the noImplicitAny and strict options enabled in the root configuration, I do not receive error notifi ...

A method for consolidating multiple enum declarations in a single TypeScript file and exporting them under a single statement to avoid direct exposure of individual enums

I am looking to consolidate multiple enums in a single file and export them under one export statement. Then, when I import this unified file in another file, I should be able to access any specific enum as needed. My current setup involves having 2 separ ...

Step-by-step guide on crafting a harmonious row of a label and a responsive button group

One of my projects involves a form that contains a list of elements. I want this form to be responsive and suitable for all screen sizes. When I initially run the project on a larger screen, everything looks good. However, when I resize the screen to a sma ...