Dealing with intricate JSON data from an API that requires mapping to a TypeScript class

Having trouble extracting collections from a complex JSON response in an API to map to local arrays in TypeScript using Angular-v5 and HTTPClient. While I can successfully consume the API and access properties of a TypeScript class called PolicyDetail, I am encountering errors with undefined values for local arrays and collection objects like policydetail.policyForms. The API response is visible in Swagger and through a Network tap, so the issue seems to lie in the mapping process.

The PolicyDetailViewModel model retrieved from the API includes various collections:

  public class PolicyDetailViewModel
{
    public string Name { get; set; }
    public string Ref { get; set; }
    public ICollection<PolicyDataViewModel> Purpose { get; set; } = new List<PolicyDataViewModel>();
    ...
}

There is also a TypeScript class called PolicyDetail with similar properties:

export class PolicyDetail extends AuditableBase
{
name:string;
ref:string;
...
}

When attempting to map the result of an HttpRequest to the TypeScript class:

export class PolicyDetailComponent {
...
getPolicyDetail() {
    this.policyDetailSvc.getPolicy(this.policyId).subscribe((result) => {
        this.policy = result; // works
        this.forms = result.policyForms; // doesn't work
        ...
    });
}
}

Issues arise when mapping forms arrays and other collection objects, resulting in undefined values. Attempts to access Policy.PolicyForms have also been unsuccessful, indicating a possible misunderstanding between TypeScript and C#.

Seeking clarification or guidance on resolving the mapping errors.

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

Answer №1

Data Parsing

Upon reviewing your query, it appears that you are dealing with a raw JSON string within your response that requires parsing into a JavaScript object...

const details = JSON.parse(result);

Ensure that the result is a string containing a valid JSON serialization for the above code snippet to function properly.

Contrast Between C# and TypeScript

Inconsistencies in naming conventions between your C# class and TypeScript may pose a challenge. For instance, if your C# class uses names like Name and Ref during serialization, ensure to match the casing in the TypeScript code...

this.forms = result.PolicyForms
//                  ^

Answer №2

The issue arose from trying to access the response using the incorrect collection names. Initially, I was receiving data for Forms but I mistakenly attempted to access it using PolicyForms. Upon changing the reference from PolicyForms to Forms, the problem was resolved and everything began functioning as expected.

 this.forms = result.policyForms;//it was not working because JSON response was coming forms:[], not PolicyForms:[].
this.forms=result.forms;//

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

Building a structured JSON request using Jbuilder

My current JSON request is returning the following data, where each person/lender has multiple inventories. #output of /test.json [ {"id":13, "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a4cecbcccac0cbc1e4c1dcc5c ...

Is there a way to adjust the background color of the clicked tab with divs and revert the others back to their original color?

<span class="row top-bar-left align-items-center" style="width: 80%; float:left"> <div tabindex="1" class="link tab" routerLink="details" routerLinkActive="active" [qu ...

Generating table rows using JSON data retrieved from an Ajax response failed due to an 'Invalid Character' error

I have managed to successfully retrieve the response as a JSON from my C# code behind. However, when trying to convert the JSON into a table using jQuery, it is throwing an error ('Invalid Character'). Here is the code snippet: $('#reports& ...

Find the average value along a specific dimension within a two-dimensional array

Consider having an array named a structured as follows: a = [[40, 10], [50, 11]] The task at hand is to compute the mean for each dimension individually, resulting in: [45, 10.5] Specifically, 45 represents the mean of a[*][0] and 10.5 is the mean of a ...

Retrieve the variable only once a response has been received from the POST request

Is there a way to update a variable in my component only after receiving a response from a POST request? Here is the code in component.ts: formSubmit() { this.sent = this.submitProvider.sendByPost(this.form); this.formSent = this.submitProvider.f ...

Tips for binding a dynamically generated array in ngModel while using ngFor for looping

I am facing an issue with binding an array dynamically in my component using ngModel. While one-way binding works fine, the model does not update when I make changes or add new elements to the array. Here is the HTML section: <div class="form-group ro ...

What is the process for implementing the "ngOnActive" life cycle hook in Angular?

Is there a way to implement a life cycle hook that will be triggered whenever my component is active on the main page, specifically on the login page? When my component is on the main page and active, I need to check if there is a login token from a previ ...

Go through a collection of Observables and store the outcome of each Observable in an array

As a newcomer to Angular and RxJS, I am facing a challenge with handling social posts. For each post, I need to make a server call to retrieve the users who reacted to that post. The diagram linked below illustrates the process (the grey arrows represent r ...

What is the quickest method for cycling through the most ancient elements in a collection? (Efficient way to execute a queue)

See edit too I'm currently working in JavaScript, but I believe any readable pseudocode may be able to help answer my question. Describing my issue might be a bit of a challenge, so feel free to ask for clarifications. I'll respond promptly and ...

What is the process for consumers to provide constructor parameters in Angular 2?

Is it possible to modify the field of a component instance? Let's consider an example in test.component.ts: @Component({ selector: 'test', }) export class TestComponent { @Input() temp; temp2; constructor(arg) { ...

Iterate through the dictionary object without any keys retrieved from the MySQL database

Table Creation: CREATE TABLE overall_risk_summary ( set_id BINARY(16) PRIMARY KEY NOT NULL, calculation_time DATETIME NOT NULL, label VARCHAR(50) NOT NULL, critical_count VARCHAR(60) NOT NULL, median_risk VARCHAR(60) ); The SQL query t ...

A step-by-step guide on using the smartsheet API to recursively fetch folders

I'm currently developing a Python backup tool for Smartsheet. My goal is to extract all the user files within my domain. However, I am unsure of how to retrieve this data while maintaining the hierarchical structure of folders as shown below: Folder ...

IE7 is throwing an error saying "Object Expected" when handling the JSON response. This issue does not

Just when I thought I was ready to launch my webapp, IE7 decides to throw a wrench in my plans! I am using the JQuery Form plugin for uploading data to my server. Everything works perfectly on Chrome and Firefox, but IE7 is giving me an "Object Expected" ...

When I execute a filter in MongoDB Compass, it displays all the rows in the result set

I am facing an issue with running a filter in MongoDB Compass. Instead of returning the specific row I am looking for, it retrieves all rows. Interestingly, applying the filter on similar example databases works without any problems. https://i.sstatic.net ...

Accessing Json data in C# Unity3D without a known key: A guide

I have recently run some code and obtained the following results. My query is related to accessing or retrieving all the data without including the auto-generated key "-M4qRmfIqhKdy643Ujye". I am specifically interested in extracting the {assetname, id, .. ...

Experience the enhanced Angular Material 10 Date Range Picker featuring the exclusive matDatepickerFilter functionality

Is it possible to use Angular Material 10 MatDateRangeInput with matDatepickerFilter? When attempting the following: <mat-form-field appearance="outline"> <mat-label>Label</mat-label> <mat-date-range-input [formGroup]=&q ...

A guide to displaying API response data in a React JS application

As a beginner in react JS, I've encountered a persistent issue. Here is the code: import React from 'react'; class SearchForm extends React.Component { async handleSubmit(event){ event.preventDefault(); try{ const url ='/jobs/ ...

Angular 11 error: Unable to access 'scrollHeight' property of null object due to TypeError

I'm hoping that someone out there can assist me in solving this puzzling issue. I am trying to obtain the full scrollHeight of the page, but for some reason, I am only getting a third of it. setSize() { let DOMScrollable = this.elementRef.nativeEl ...

Substituting identical values with different keys in a JSON object

Managing JSON key values can be tricky, especially when trying to replace them one at a time. The challenge arises when multiple keys have the same value in the JSON body. The goal is to update only one key value at a time, even if the values are identical ...

Ionic JavaScript function runs independently of promise resolution

Within my ngOnInit on a page, I have a method that is meant to fetch data. However, it seems like the other methods in the chain are executing before the fetch data process is complete. Here's a snippet of the code: ngOnInit() { this.devicesinfo.fetc ...