What is a typical data transformation pattern used in TypeScript and Angular 2?

Developing an Angular 2+ application using TypeScript.

I've been structuring objects for storage in a data source, including helper methods within them. I have successfully saved these objects. ORIGINAL CLASS DESIGN EXAMPLE

export class Order {
    readonly orderNumber: string;
    amount: number;
    shortCode: string;
    readonly dateCreated: string;

    constructor(){
        this.orderNumber = cuid();
        this.dateCreated = moment().format();
    }

    incrementAmount(): void {
        this.amount += 1;
    }

RESULTED OBJECT:

{ 
  amount: 74.22,
  dateCreated: '2017-04-03T21:23:49-04:00',
  orderNumber: 'cj12v2rf50000zoguviraoik9',
  shortCode: 'SJLLDE' 
}

However, upon retrieval, the objects are not in their original form. It seems counterintuitive to manually extract and rebuild objects field by field. Instead, working with one known object might be more efficient for type usage and enhanced functionality.

Is it common practice in this ecosystem to transform returned data from services back into original objects?

If so, are there any resources available that discuss common approaches for achieving this?

Answer №1

When data is returned from the backend, it's essential to convert it from a JSON object into the appropriate model object.

Here's my typical approach:

let item: Item = new Item(itemJsonObject);

To achieve this, you'll need to modify your constructor as follows:

export class Item {
    readonly itemCode: string;
    price: number;
    category: string;
    readonly dateAdded: string;

    constructor(data){
        if(data !== null) {
          this.itemCode = data.itemCode;
          this.price = data.price;
          this.category = data.category;
          this.dateAdded = data.dateAdded;
        } else {
          this.itemCode = generateId();
          this.dateAdded = moment().format();
        }
    }
}

This methodology has been effective for me thus far. Best of luck!

Answer №2

If you're looking for a reliable solution to parse JSON data, consider utilizing the third-party library called "ta-json." You can find more information about it here: https://www.npmjs.com/package/ta-json.

import { JSON, JsonObject, JsonProperty } from "ta-json";
@JsonObject()
export class Purchase {
  @JsonProperty()
  readonly purchaseCode: string;
  @JsonProperty()
  amount: number;
  @JsonProperty()
  productCode: string;
  @JsonProperty()
  readonly dateOrdered: string;

  constructor() {
    this.purchaseCode = generateCode();
    this.dateOrdered = getFormattedDate();
  }

  increaseAmount(): void {
    this.amount += 1;
  }
}

let purchase = new Purchase();
console.log(purchase.amount);
let dataToSave = JSON.stringify(order);

let parsedData = JSON.parse<Purchase>(dataToSave);
parsedData.increaseAmount();
console.log(parsedData.amount);

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

Can you share any recommendations or instances of modifying data within HTML tables using Laravel?

Has anyone ever needed to directly edit and update data in a HTML table using Laravel? I have successfully created "create" tables for different tasks, but I'm interested in being able to modify the data directly on an "index" page. While there are ...

Struggling with TypeScript compilation in a Vue.js project? Encounter error code TS2352

Here is my code snippet from window.ts import Vue from 'vue' interface BrowserWindow extends Window { app: Vue } const browserWindow = window as BrowserWindow export default browserWindow Encountering a compilation error Error message: TS2 ...

Angular - Using HttpClient for handling POST requests

The example provided in the official Angular HttpClient documentation demonstrates how to make a POST request to a backend server. /** POST: add a new hero to the database */ addHero (hero: Hero): Observable<Hero> { return this.http.post<Hero&g ...

What is the best way to showcase JSON keys in Vue.js?

I have a JSON structure that resembles the following: { "data": [ { "name": "someName", "link": "http://somelink.com", ], "relevantArray": [ { "keyIWant": ...

Attempting to integrate a chatroom name entered by the user using a combination of Ajax and Python

Despite reading numerous textbooks on computer science, I have been struggling with sending ajax form data to Python and checking it in a dictionary before parsing it into a JSON object. The concept of dictionaries with key-value pairs is clear; however, a ...

Original: Placeholder Text With $scope.Array and HTML DIVRewritten: Text

How can I display default text as a placeholder in a drop-down menu without including it as an option? HTML <div class="form-group"> Upload new file to: <select class="form-control" ng-model="selectedDocumentType" ng-click="s ...

Merging distinct objects/values in AngularJS/Javascript to create a straightforward list

I possess a dynamically generated, multi-level nested object containing DISTINCT values. My goal is to flatten it (using either AngularJS or vanilla JS) and produce a straightforward array or object for each key/value pair. For example, if the object takes ...

The process of upgrading all dependencies to a particular version

I need guidance on upgrading a project from Angular 6 to version 7. The challenge lies in updating numerous dependencies as well. Most tutorials available only cover upgrading to the latest version (v8), rather than a specific one. Can anyone provide ins ...

Using a loop to draw lines on a canvas

Gaining a preliminary understanding of java-script and canvas. I have managed to create steps and draw the initial two lines. I aim for this sequence to repeat 7 times. 7 p1's and 6 p2's in essence, it descends 7 times and moves across ...

Using JavaScript to submit the value of a checkbox

I'm currently working on a form submission using JavaScript that includes both text input and two checkboxes. <script> function SubmitFormData() { var preferredLocation = $("#preferred_location").val(); var relocation = []; ...

"Navigating through events with confidence: the power of event

Imagine I am developing an event manager for a chat application. Having had success with event maps in the past, I have decided to use them again. This is the structure of the event map: interface ChatEventMap { incomingMessage: string; newUser: { ...

Which specific technological platform or framework would be most suitable for constructing a similar project?

https://i.stack.imgur.com/LL1g9.png Looking at the image provided, my goal is to allow users to navigate between pages on the Home page without having to refresh the entire browser window. I believe this can be achieved using Ajax technology, am I correct ...

Is there a way to translate IBM floating point data into JavaScript numbers?

I am interested in extracting data from a legacy file format that utilizes IBM floating point numbers. These numbers were commonly used on the IBM System/360 mainframe computer system. Now, I am hoping to leverage this information within a JavaScript progr ...

Tips for enabling the `ignoreUndefinedProperties` feature in Node.js

I'm currently in the process of creating a REST api for my Node.js and Express application. However, I keep encountering an error stating that properties are undefined whenever I attempt to send a request. How can I go about enabling 'ignoreundef ...

The act of looping with for loops can be quite disruptive to

I need to display some basic 3D objects (specifically THREE.Sphere which contains 1-30 other THREE.Spheres with RGB color and no texture) in a somewhat real-time animation. The rendering process is quick, but I am facing issues with simple iterative calcu ...

The binding in Knockoutjs is working properly, but for some reason the href attribute in the anchor tag is not redirecting to

Here is the HTML code snippet I am working with: <ul class="nav nav-tabs ilia-cat-nav" data-toggle="dropdown" data-bind="foreach : Items" style="margin-top:-30px"> <li role="presentation" data-bind="attr : {'data-id' : ID , 'da ...

Can the optionsText be shown while saving the optionsValue in a dropdown menu?

Here is the code snippet I am currently working with: var model = function() { this.nameSomething = ko.observable(''); this.nameId = ko.observable(0); }; var vm = (function() { var myList = [{ id: 1, type: 'foo1'}, { id: 2, ...

Is it possible to utilize ag-grid's API to filter multiple checkbox values simultaneously?

I am currently utilizing angularjs and have implemented a series of checkboxes to filter my ag-grid. So far, I have successfully utilized radio buttons and the api.setQuickFilter method for filtering based on individual values. However, I am facing an iss ...

Organizing a Javascript project for development and production with the help of npm and grunt

I have been working on structuring the JavaScript files in my project. I opted to use NPM for managing modules and Grunt for concatenating and compressing js and css files for deployment purposes. Here is the current structure I am using: -[project root ...

Issue encountered while attempting to install datagrid library with Nuxt3

Currently, I am working on a Nuxt3 project and attempting to integrate the " @revolist/vue3-datagrid" library. Following the instructions provided in the library's documentation, I executed the command "npm i @revolist/vue3-datagrid --save". Unfortuna ...