What is the outcome of the conversion process?

I am encountering an issue where I am trying to retrieve a Coupon object from the Back-End, but instead of getting the desired Coupon type in the Front-End, I am receiving an 'Object' type.

It seems that the problem lies in the conversion process between the Back-End and the Front-End.

JSON representation of the Coupon from the Back-End:

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

Coupon Entity in the Front-End:

export class Coupon {

      amount: number
      category: number
      endDate: string
      id: number
      imageURL: string
      price: number
      startDate: string
      title: string

     
      constructor(
                id: number,
                // companyId: number,
                title: string,
                startDate: string,
                endDate: string,
                category: number,
                amount: number,
                price: number,
                imageURL: string
      ) {
                this.id = id
                // this.companyId = companyId
                this.title = title
                this.startDate = startDate
                this.endDate = endDate
                this.category = category
                this.amount = amount
                this.price = price
                this.imageURL = imageURL
      }
}

GET request:

getCompanyCoupons() {
  const params = new HttpParams()
    .set("token", this.token);
  return this.http.get < Coupon[] > ('http://localhost:8080/api/company/get_company_coupons', {
    params
  })
}

Usage of the request:

fetchAllCoupons() {
  this.storagService.getCompanyCoupons()
    .subscribe(coupons => {
      this.coupons = coupons
      console.log(this.coupons)
    })
}

Answer №1

Runtime does not recognize Typescript types, and JSON cannot represent Javascript classes.

If you wish to maintain the class structure during data transmission, JSON is not a viable option. It seems there isn't a widely used format that handles class names in serialization/deserialization.

The best approach may be to acknowledge that classes will be converted to plain objects when JSON serialized. If you intend to convert them back into classes on the receiving end, some manual intervention will be necessary.

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

Aurelia CLI encounters difficulty importing chart.js when using TypeScript

Currently, I am utilizing typescript with aurelia/aurelia-cli. After npm installing chart.js, I proceeded to add it to my aurelia.json file like so: "dependencies": [ ... { "name": "chartjs", "path": "../node_modules/chart.js/d ...

Angular 2: @ContentChild - specifically limited to direct descendants

To simplify and be concise, let's illustrate with an example: <my-accordion> <my-title>My accordion</my-title> <my-accordion-item> <my-title>My accordion item 1</my-title> <my-content> ...

Completing a submission form in a separate module

I've developed a model-based form within a component, but the submit button is located in a different component. When the button is pressed, the following function is activated: @Input() form: any; ... if(this.form.valid) this.saveD ...

Tips for adjusting the preferred view resolution for a seamless blend of GSP and JSON views

I'm currently managing a grails 3.3.8 application that utilizes the angularjs profile. Both the REST API and angularjs assets are integrated within the same grails application. At the moment, I am not looking to separate them into two distinct applic ...

Testing to submit a form using ReactiveForm can be done by reloading the form while it is being submitted

A tutorial I came across titled "Make Your Angular Form’s Error Messages Magically Appear" sparked the beginning of my journey. The tutorial featured a simple form with just one input field and one button. To trigger additional events on a lower level, I ...

When defining a type in Typescript, the argument of type 'never[]' cannot be assigned to a parameter of type 'never'

Currently, I'm delving into the world of Typescript by following a tutorial. As part of my learning process, I decided to try out the code below: interface Task { title: string; completed: boolean; } type AppState = Array<Task>; const Tas ...

The dynamic grid in an md-tab is failing to load the definitions in Angular SlickGrid

My Angular Slick Grid component is not loading within the md-tab element. The child component will only be created after the md tab is initialized. I have configured the tab settings in the ngOnInit method of the child component's TypeScript file. I ...

Exploring the new features of VueJS 3 with Typescript

Just starting out on my first project using typescript and encountering some interesting challenges. In my Login.vue file, I have the following method: const doLogin = async () => { try { const { email, password } = credentials.value; ...

Improving Accessibility in Angular 10 by Confining Focus within Modals

I'm currently working on updating my existing modal popup to ensure ADA compliance. I am using a user-defined handleTabKeyFocus() function to manage the keyboard Tab focus within the modal container. However, the querySelector selector always returns ...

Steps to ensure checkboxes are enabled for selection only when another box has been checked

Consider having 3 checkboxes: 1 'parent' checkbox and 2 'child' checkboxes. If the parent checkbox is selected, you should be able to select either or both of the child checkboxes. If the parent checkbox is deselected, neither of the ...

Issue: Angular CLI version 10.1.0 or newer is requiring a `tsconfig.base.json` file, which is not found

Currently working on my Angular 11 project, I am faced with the challenge of transitioning from tslint to eslint. When attempting the command below: ng add @angular-eslint/schematics An error arises: Error: Angular CLI v10.1.0 and later (and no tsconfig ...

What is the correct way to implement ramda's ifElse function in typescript?

My attempt to enhance the typing of ifElse in Ramda, which currently has a type definition as follows: export function ifElse(fn: Pred, onTrue: Arity2Fn, onFalse: Arity2Fn): Arity2Fn; However, I quickly reached the limitations of TypeScript (or rather my ...

Bespoke Socket.io NodeJS chamber

I am currently developing an application involving sockets where the requirement is to broadcast information only to individuals within a specific room. Below is a snippet of the code from my server.ts file: // Dependencies import express from 'expre ...

Can anyone help me troubleshoot createPortal in NextJS with TypeScript?

Currently, I am working on a toy project using Nextjs and Typescript. However, I have encountered an issue while attempting to create a Modal using createPortal. Whenever I click the button, nothing happens. Upon investigation, it seems that the value ...

What is the best way to divide a string into an array containing both linked and non-linked elements?

I'm struggling to find the right solution to my problem. I need to create a view that is enclosed in a clickable div. The content will consist of plain text mixed with clickable URLs - the issue arises when clicking on a link also triggers the method ...

Instructions for creating a cutout on a doughnut chart using ng2-charts

Can someone help me with setting configuration options on my doughnut chart using ng2-charts? Specifically, I am trying to set the cutout property on the chart. Despite going through the documentation for charts-js and ng2-charts, I haven't been able ...

Combining string types with spaces and accepted types in TypeScript, potentially recursive

type AcceptedClass = "one" | "two" | "three"; type ClassNameType = `${AcceptedClass} ${ClassNameType}`; const className: ClassNameType = "one two three"; const className2: ClassNameType = "two one three one th ...

Discovering the steps to showcase _app.tsx within next.js 13 through module federation

I am faced with a situation where I have two Next.js 13 projects: Homepage and Admin Panel. My goal is to showcase the entire Admin Panel (specifically _app.tsx) and embed it within Homepage. To achieve this, I have set up both projects utilizing @module-f ...

Is there a way to merge two generic keys for a specific data type?

I've been working on creating a TypeScript helper for React's useState hook. The goal is to simplify components' (functions) arguments/props like the following: import { type Dispatch, type SetStateAction } from 'react'; export co ...

There was an unexpected error: The required package "@esbuild/darwin-arm64" could not be located and is essential for esbuild to function properly

After recently upgrading to Angular 17, my application runs smoothly. However, I encountered an error when building the package using ng build: An unhandled exception occurred: The package "@esbuild/darwin-arm64" could not be found, and is needed ...