Creating TypeScript models from a JSON response in React components

My Angular 2 application retrieves a JSON string, and I am looking to map its values to a model. According to my understanding, a TypeScript model file is used to assist in mapping an HTTP Get response to an object - in this case, a class named 'CustomObject'.

This is the TypeScript model file I have created for TypeScript to recognize:

export class CustomObject {
    public Name: string;
}

Here is a snippet of what the JSON string looks like (slightly modified from Chrome dev tools):

"{
   "EventType": 3,
   "Description": "Test Description",
   "LocationName": "DefaultLocation",
   "Name": "TestName"
}"

I aim to take the 'Name' value ("TestName") from the JSON string and map it to an existing variable 'activeCustomObject' declared in my home.ts file, which is initially set to null:

public activeCustomObject: CustomObject = null;

However, after fetching the JSON response using the HTTP Get method, when I try to access {{activeCustomObject.Name}} in my HTML file, nothing gets printed. I have ensured proper imports and providers are set up.

This is how I am subscribing:

this._customObjectService.getCustomObject()
    .subscribe(res => {
        this.activeCustomObject = res;
    });

And here is how I am calling the GET method:

getActiveCustomObject() {
    return this._http.get('/test/customobject')
        .map((response) => {
            console.log(response);
            return response.json;
        });
}

Why does accessing {{activeCustomObject.Name}} not print anything in my HTML? The Chrome dev tools show that the JSON is returning a valid string with the necessary data (including the name). Since I intend to use other values from the JSON string, I cannot just have the HTTP GET return the name field alone. I need to understand why the returned JSON string is not correctly mapped to the Custom Object variable.

Answer №1

It seems like the issue might be due to the asynchronous loading of your data. There could possibly be an error in your JavaScript console...

One solution you can try is using the Elvis operator in this manner:

{{activeCustomObject?.Name}}

Another problem I noticed is that you should call the json method on the response, not just a property:

getActiveCustomObject() {
  return this._http.get('/test/customobject')
    .map((response) => {
        console.log(response);
        return response.json(); // <-----------
    });
}

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

Is there a way to modify the color of the JSON `Key` in Sublime Text2?

After some adjustments, I've included the following code snippet in my color scheme named `custom.tmTheme`: <dict> <key>name</key> <string>JSON Key</string> <key>scope</key> ...

How can I extract data from an XML file and include it in a JSON file using GulpJS?

Being relatively inexperienced with Gulp/Node programming, I am facing some difficulties while trying to accomplish a simple task :) Within my XML file, there exists a node like the following: <widget version="1.1"></widget> My goal is to ext ...

Issue with 'else if' statement in React Typescript: Unneeded 'else' block following 'return' statement

I am encountering an issue with the else if statement below. Even after removing the last pure Else statement, I am still getting an error on ElseIf from Lint. How can I fix this problem? Error message: Unnecessary 'else' after 'return&apo ...

How can you ensure a script runs only once another script has completed its execution?

Consider the following code snippet I created to illustrate my idea: var extract = require("./postextract.js"); var rescore = require("./standardaddress.js"); RunFunc(); function RunFunc() { extract.Start(); console.log("Extraction complete"); ...

Using Vuelidate with Vue 3, vue-class-component, and TypeScript combination

Is there anyone who has successfully implemented Vuelidate with Vue 3 using the Composition API? Although Vuelidate is still in alpha for Vue 3, I believe that if it works with the Composition API, there must be a way to make it work with classes as well. ...

Upon pressing enter in the input box, the page will redirect to localhost:3000/

Utilizing the NewYorkTimes API to retrieve search queries from an input field. However, upon hitting enter after entering a query, my localhost reloads and redirects to localhost:3000/?. After using console.log(url) in the console, I confirmed that the UR ...

Tips for converting JSON data into a C# object with dynamically generated properties

I'm struggling with ensuring that my subject accurately conveys my question, but I hope it does. Currently, I am immersed in a project that necessitates integration with Mailchimp, and one of the properties of the Member's object is known as "me ...

Unexpected obstacles encountered when implementing the jqTouch JavaScript/AJAX combination on Android

In jqtouch, I'm using vanilla ajax calls to load multiple pages: <li class="arrow"><a href="folder/another/somepage.html" >BRAVIA HDTVs</a><small class="counter">2</small></li></li> I want to incorporate a v ...

Eslint is back and it's cracking down on unused variables with no

I've configured eslint to alert me about unused variables rules: { '@typescript-eslint/no-unused-vars': ['error', { args: 'none' }], } Presently, I have a TypeScript class structured like this: import { User } from &ap ...

Merging classes from several files into a unified namespace in typescript

When working with typescript, my goal is to instantiate a class by using its name as a string. After some research, I discovered the following approach: const googlecommand = Object.create((Commands as any)['GoogleCommand'].prototype); This lin ...

What is causing the permissions in firestore to not function properly?

My custom code changed(){ let reference = db.collection('messages').orderBy('timestamp') // listen for changes to the 'messages' collection reference.onSnapshot(snapshot => { snapshot.docChanges().forEach(change => ...

The validation for Australian mobile numbers should include the option to have spaces between the digits

How can I validate a mobile number properly? The first text input should start with 04 It should have a total of 10 digits, including 04 (e.g. 0412345678) Below is my input field: <form name="uploadForm"> <input type="tel" name="MobileNumber" ...

Stopping npm build when ESLint detects warnings

Dealing with a particularly immature team, I am determined to make the react-typescript build fail whenever ESLint issues warnings. src/modules/security/components/ForgotPasswordBox/index.tsx Line 8:18: 'FormikHelpers' is defined but never use ...

How can I add a string before a hashtag(#) in AngularJS URLs?

Can we add a prefix to the # symbol in angular.js URLs? For instance: let's say we have a site: http://example.com/ then when I click on the CSharp page, it redirects to http://example.com/#/csharp when I click on the AngularJS page, it redi ...

Difficulty comprehending the response from an AJAX post is being experienced

I'm currently working on a website and facing an issue connecting JavaScript with PHP using AJAX. Specifically, I'm struggling with reading the AJAX response. My PHP script contains the following code: <?php echo "1"; In addition, I have a ...

Continuously providing service within the application

In the process of developing my app, I have implemented a feature that sends the user's geolocation data to the server (given proper permissions). Currently, this geolocation data is only pushed to the server when the user navigates to the account pag ...

Prefixes for logging - Consider using the not-singleton technique or another approach

I am currently developing a logging helper for Node.JS that includes several exported functions such as error and warn. For instance, I have two other scripts called test1 and test2 which make use of this "module". When initializing my logging module us ...

Determine in React whether a JSX Element is a descendant of a specific class

I am currently working with TypeScript and need to determine if a JSX.Element instance is a subclass of another React component. For instance, if I have a Vehicle component and a Car component that extends it, then when given a JSX.Element generated from ...

Finding a specific number of records from an array of objects that also contain their own arrays can be achieved by using a combination of

I need a way to retrieve the last record from an ArrayList, but I'm facing a challenge because my ArrayList consists of a custom POJO class with its own array. This makes it difficult for me to determine the total number of records in the ArrayList. ...

Encountering an error in Angular UI when trying to utilize the $modal within my service dependency injection, causing

I have encountered a problem with my AngularJS and UI-Bootstrap code. In the following service, I am injecting $modal but it is showing as undefined. Interestingly, when I inject $modal into a controller instead, everything works perfectly. Can someone ex ...