Unable to utilize Angular object due to the JSON format of the data

I'm facing an issue in my Angular 4 application with TypeScript. I am using a get() method and a subscribe() method to receive a remote object in JSON format and deserialize it to match a class structure. When all the class data fields are mirrored in the JSON file, everything seems to work fine as I can access and use these object data fields in my HTML template.

However, when I try to add new methods or data fields to this class, the HTML template does not display these new additions. I am unable to understand why this is happening and how to solve this problem.

Here's an example:

// In ExampleObject.ts
export class ExampleObject {
property1: string;
property2: string;
}

// In another file
exampleObject: ExampleObject;

getCurrentObject() {
  this.objectService.getObjcet().subscribe(
  data => this.exampleObject = data,
  error => {
    console.log('some error found: ' + error);
});

If I try to add a method in ExampleObject like this:

export class ExampleObject {
property1: string;
property2: string;

getHello() {
 return 'Hello'; 
}
}

The following instructions in the HTML template work:

{{exampleObject.property1}}
{{exampleObject.property2}}

But this instruction does not work:

{{exampleObject.getHello()}}

Answer №1

It has been pointed out in the comments that without an instance of ExampleObject, you won't be able to execute its methods.

The getCurrentObject method is setting the retrieved data to a layout similar to ExampleObject, but it's not an actual instance of it. This is why you're unable to call any methods or add new properties.

To address this issue, you would need to follow the suggestions provided in the comments.

getCurrentObject() {
  this.objectService.getObjcet().subscribe(
  data => this.exampleObject = Object.assign(new ExampleObject(), data),
  error => {
    console.log('some error found: ' + error);
});

NOTE: I haven't verified this syntax. If you create a plunker, I can confirm.

In this line:

this.exampleObject = Object.assign(new ExampleObject(), data)

A new ExampleObject is created and its properties are assigned based on the values in data.

Did you give this approach a try?

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

When working with an observable in an Angular Material table, the *ngIf directive may not function as expected

Attempting to utilize an Angular Material table with expandable rows, specifically to display information based on screen width reaching a particular breakpoint. Utilizing an observable isHandSetPortrait$ that is subscribed to in the HTML to determine if t ...

The TypeScript datatype 'string | null' cannot be assigned to the datatype 'string'

Within this excerpt, I've encountered the following error: Type 'string | null' cannot be assigned to type 'string'. Type 'null' cannot be assigned to type 'string'. TS2322 async function FetchSpecificCoinBy ...

The Jest test encounters failure when attempting to use an absolute path to load an SVG image

Currently, I am developing a Typescript React application using Vite. To test my app, I have implemented Jest and babel. An important aspect of my setup is the use of absolute paths throughout the entire application. Interestingly, when I run tests with r ...

Once StoreModule.forFeature(...) has been included, the stored data becomes inaccessible

I am currently working on multiple projects within a single Angular 8 app... Previously, I had @ngrx/store implemented in only one project, but now I have added @ngrx/store to every project. Due to having multiple stores, I now need to import StoreModule.f ...

Trying out the results of angular services

Seeking assistance in understanding the current situation: I believe a simple tour of heroes app would be helpful in clarifying, I am looking to set up some tests using Jest to verify if the behavior of a service remains consistent over time. This is ho ...

Uncovering the potential of JSON data using PHP

I recently retrieved information from a different website in JSON format. You can see what I found here: Specifically, I am looking to obtain the values for kills and deaths from this data set. I attempted using the php function json_decode() on this info ...

How to extract JSON data without a specified object key in Java

Could you assist me with parsing this JSON data received as a response from a REST API call into key-value pairs? The JSON does not have object names, includes nesting, and lacks new lines between records. The goal is to extract the information and impor ...

The Typescript function unexpectedly returns a NaN value even though it should be returning a

Having an issue with my countdown timer function: startTimer(duration) { this.myTimer = duration; setInterval(function () { this.myTimer--; console.log("TIMER: " + typeof(this.myTimer) + " " + this.myTimer); }, 1000); } When I ...

Determine the percentage using jQuery by considering various factors

I am facing an issue with the following code snippet: <script type="application/javascript"> $(document).ready(function () { $("#market_value").on("change paste keyup", function() { var market_value = par ...

Unable to parse JSON elements using jQuery

Currently, I have an unordered list containing customer names that are retrieved from a JSON file. I am trying to implement a click event using jQuery, but it seems to be having trouble reading it. While the list appears correctly in the HTML source file, ...

Java 8 Streams and Multi-level Grouping with GroupingBy

I am looking to create a JSON output structure as shown below { "account":{ "Alpha":{ "OLD":{ "long":"zerozerooneO", "short":"001O" }, ...

The data type 'number' cannot be assigned to the data type 'undefined'. Error code: ts(2322)

I encountered an issue where it's giving me an error stating that type number cannot be assigned to type undefined on the last digit (1) in scale={[1.618, 1, 1]}. Can anyone help me figure out how to resolve this TypeScript error? "use client&quo ...

Troubleshooting TypeScript errors in Cassini with Google Chrome

While troubleshooting a .NET 4.6.1 web application with Cassini in Visual Studio 2015 version 14, update 3, I encountered an error on a page that utilizes TypeScript: Refused to execute script from 'http://localhost:53049/Scripts/app.ts' because ...

Tips for bringing in Cassandra driver types in TypeScript?

In the documentation for the Cassandra driver, they provide code examples like this: const Uuid = require('cassandra-driver').types.Uuid; const id = Uuid.random(); However, when attempting to use this in Visual Studio Code, the Uuid class type ...

Interact with Node.js server to fetch JSON data from Python and display it on an HTML client using Ajax

Seeking a way to retrieve JSON data in my HTML page using Ajax, I have a Node.js server set up for handling requests. The JSON data is generated by Python code on the server. Is it worth saving the JSON in a database for access? Seems overly complicated ...

Eliminate duplicate entries from a JSONArray in Java

In the given JSON array below, there are multiple objects with two keys: 1) submitted_datetime 2) value The task is to filter out those JSON objects where the value is repeated and retain only the most recent one. The goal is to keep duplicate values ...

"File compatibility issue: JSON file updated in Chrome is not functioning properly in Firefox

Hey there! I'm currently working on editing and saving some data in a JSON file that already exists. Check out the code below: var newData = { mailTo: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="63020100235251504 ...

Retrieving the returned value from an Observable of any type in Angular Typescript (Firebase)

I am working on retrieving data from my Firebase User List using the following code: currentUserRef: AngularFireList<any> currentUser: Observable<any>; var user = firebase.auth().currentUser; this.currentUserRef = this.af.list('usuarios ...

Parsing Json into Kotlin Data Class with GSON

I am working with a Java POJO class that looks like this: class Topic { @SerializedName("id") long id; @SerializedName("name") String name; } In addition, I also have a Kotlin data class structured as follows: data class Topic(val id: L ...

Updating button color dynamically using Angular 2

I am working on a project using angular 2 and typescript. I am looking to customize the background color of my buttons based on a variable. <div> <button md-button>1. Choose travel</button> <button md-button>2. Choose seats< ...