Retrieve the instance of the "Hydrate" class from a JSON object

I am currently working with a class that looks like this:

import { AccountRow } from './account-row';
export class Account {
  id?: number;
  name: string;
  rows: AccountRow[];
  public getTotal?(): number {
    let total: number = 0;
    if (!this.rows || this.rows.length == 0) {
      return total;
    }
    for(let r of this.rows) {
      total += r.amount;
    }
    return total;

  }
}

When trying to populate it with the following code:

export class HomePage {
  accountForm: FormGroup;
  addRowForm: FormGroup;
  activeAccount: Account;

  constructor(public navCtrl: NavController) {
    // Fixture for testing
    this.activeAccount = {
      name: "January balance",
      rows: [
        { description: "Car insurance", amount: 45.5, date: new Date() },
        { description: "Car insurance", amount: -20.5, date: new Date() }
      ]
    };
    console.log(this.activeAccount.getTotal());

  }
}

Although values are assigned correctly, it appears that object assignment is causing the getTotal method to be lost. When attempting to execute the code, an error is thrown:

Error: Uncaught (in promise): TypeError: this.activeAccount.getTotal is not a function
TypeError: this.activeAccount.getTotal is not a function

I am curious to know if there is a way to achieve this without losing instance methods or having to implement an initializer constructor or factory method.

Answer №1

It is not possible to achieve this in the programming language directly. The recommended solution is to utilize the class-transformer library, which can be found at https://github.com/pleerock/class-transformer.

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

The function that iterates through the 'categoria' state and returns a new array is not functioning properly

Having difficulty with the object of a function using .map(). It works when the code is used directly, but not when put inside a function. For example: if(this.state.cat){ return _.map(this.state.cat, categoria => { if(this.state.search_ ...

Alias in webpack for Typescript modules

I'm facing an issue where I need to assign an alias for 'Hammer' in my code. I've already included the necessary paths in my tsconfig file as shown below: { "compilerOptions": { "declaration": true, "noImplicitAny": false , ...

What is preventing me from utilizing maxLength with input fields?

Whenever I try to include maxLength in an input field, I encounter an error message stating "Invalid DOM property maxlength". Should I be using maxLength instead? Here's a link to the code: https://codesandbox.io/s/nkz2kwl7y0 ...

Enhance tns-platform-declarations with NativeScript

I am working on a NativeScript project and I am trying to incorporate the RecyclerView from Android Support Library. I have added the dependency in the app/App_Resources/Android/app.gradle file: // Uncomment to add recyclerview-v7 dependency dependencies ...

Availability of variables and declaration of functions

I'm having trouble accessing a variable in my Angular project. I am new to this, so please bear with me. Here's an overview of my project: app.component.html: <div> <ul> <li *ngFor='let var1 of Fcomponent' >{{var1}} ...

How can I store various data types in a single array in TypeScript?

I have a scenario I need help with. Let's say we have two interfaces, Cats and Dogs. How can I create an array that can store both Cats and Dogs? interface Cats { name: string; age: number; } interface Dog { owner: string; } const cat1: Cat ...

Mistakes found in the code post-building with Angular CLI (ng build)

Hello, I am a beginner in Angular and I am currently trying to set up a new project in Angular using angular/cli. I have followed the steps below to set up an Express server with Angular as the frontend: I first installed angular/cli and then used the com ...

Using an exported function with parameters as a filtering mechanism for the material datepicker

I am currently facing an issue while trying to set a const exported function in a material datepicker filter with parameters. When I try to set the parameters in my component, the function gets executed and returns the result (a boolean) instead of simply ...

Utilizing Typescript and Jest to prevent type errors in mocked functions

When looking to simulate external modules with Jest, the jest.mock() method can be utilized to automatically mock functions within a module. After this, we have the ability to modify and analyze the mocked functions on our simulated module as needed. As ...

Can you showcase two distinct perspectives on a single page?

One of my components has nested ngFor directives looping through an array of users and their posts. I have a view link within this element, and when clicked, it should show detailed information about both the user and the post. However, the current setup i ...

How to Set Focus on an Input Field in an Angular 2 Modal

I'm currently working with modals in an angular project and I have a requirement to focus on a specific field within the modal. This particular field is a part of a @component: Autocomplete.html <div #autocomplete> <input #input requ ...

The default behavior of Angular-Keycloak does not include automatically attaching the bearer token to my http requests

I'm currently working on integrating keycloak-angular into my project, but I'm facing an issue with setting the bearer token as the default for my HTTP requests. "keycloak-angular": "9.1.0" "keycloak-js": "16.0 ...

Angular - Show user information on homepage post authentication

Utilizing Angular 7 and Laravel 5.8 for user Login implementation where Laravel serves the endpoint to Angular. The user login functionality has been successfully created, however, unsure about displaying the logged-in username. User.ts export class User ...

The specified type '{ songs: any; }' cannot be assigned to the type 'IntrinsicAttributes' in NEXTJS/Typescript

I am currently working on a straightforward script. Below is the index.tsx file for my Next.js application: import type { NextPage } from 'next' import SongsList from '../components/SongsList/SongsList' import { GetStaticProps } from & ...

What is the process for integrating mobiscroll into an Angular project using a customized username?

After installing the mobiscroll trial in my angular project, I decided to reinstall it with a new username. Despite attempting to remove the library and using the command "mobiscroll config angular", I encountered an issue where it was still logging in w ...

How can I use Angular 4 typescript to deactivate a button based on the value of a boolean variable?

I am looking to define a function in TypeScript called 'isActive()', which I will then invoke on a button within my HTML file. Additionally, I have already declared a boolean variable named 'isActive'. In this scenario, I have two butto ...

The default value is not displayed in the Angular dropdown menu

When using regular html select menus, if you create an option element with selected and disabled attributes and provide text for that option, the text will be displayed by default in the select menu. Below is a basic example of HTML code: <select name= ...

Tips for compacting JSON in Typescript

I have encountered a challenge in my coding where we are dealing with quite large data objects. I am exploring the possibility of compressing these data objects to reduce payload size. For instance, if our input json size is 2 MB, can it be compressed to a ...

Guide to setting up .env Variables on a DigitalOcean Ubuntu droplet

After deploying my Node.js app on a DigitalOcean Ubuntu droplet, I encountered the need for variables from my .env file. How can I go about creating these variables within the DigitalOcean droplet? ...

Is there compatibility between Ionic and Kindle Fire/Galaxy Tab devices?

Are there specific challenges when developing in Ionic for Kindle Fire and Galaxy Tab devices? Do the code/assemblies and target Framework differ from other Android devices? ...