Data object constructor is not triggered during JSON parsing

Currently, I am retrieving data from a server and then parsing it into TypeScript classes. To incorporate inheritance in my classes, each class must be capable of reporting its type. Let me explain the process:

Starting with the base class

import { PageElementType } from './page-element-type'

export class PageElement {
    pageElementType: PageElementType;
    constructor(aPageElementType: PageElementType) { 
        this.pageElementType = aPageElementType; 
    }
}

Moving on to a derived class

import { PageElement } from './page-element.model'
import { PageElementType } from './page-element-type'

export class Metadata extends PageElement {
    id: number;
    body: string;

    constructor(){
        super(PageElementType.metadata);
    }
}

Now, here's the service function I use to parse the data

getExam(){
    let exam = this.http.get('http://orangeberry.hopto.org/api/Exam/1')
    .map((response:Response) => <Exam>response.json())
    .do(data => console.log(data));
    return exam;
}

I seem to be receiving plain objects instead of the desired functional objects that adhere to the class definition. What would be the simplest and most direct approach to address this issue?

Answer №1

Using a cast in static code analysis is simply a suggestion and does not impact runtime execution.

If you want a value to be an instance of a specific class, you must manually create that instance like so:

.map((response:Response) => new Test(response.json()))

In this example, the constructor of the Test class extracts properties from the JSON data.

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

Combining a union within the json_agg function alongside the json_build_object operation

CREATE TABLE sample_table1 ( identifier integer, content text); INSERT INTO sample_table1 VALUES (1, 'abc'), (2, 'def'); CREATE TABLE sample_table2 ( identifier integer, content text); INSERT INTO sample_table2 VALUES ...

A guide on iterating through a JSON object in Vue and Javascript to retrieve keys and values, checking if they are either distinct or null

Looking for a way to iterate through a JSON object that may or may not have properties fields, which can be null or contain various configurations. I need to display it in a code block. Below is the example JSON data: "grade": [ { ...

Utilize JavaScript to seamlessly play a Spotify track within the Spotify client without disrupting your current

A little while back, I recall the simplicity of clicking play on a song within a website and having it instantly start playing on my computer without any additional steps. It was seamless and effortless. My goal for my website is to have music start playi ...

Is there a way to display the entire stack trace in Mocha when testing Promises and an error occurs?

Imagine I have a small specification like this: describe("feature", () => { it("does something", () => { return myPromiseBasedFn().then(result => { expect(result).to.eql(1); }); }); }); At the moment, when the promise is reject ...

Building a frontend and backend using Typescript with a shared folder for seamless integration

I am currently exploring the idea of transitioning to TypeScript, but I am facing challenges in figuring out how to create a shared folder between the frontend and backend. This is the project structure that I have come up with: frontend - src -- server.t ...

Clear SELECT After Submission

I have a jQuery script and need a function to reset the SELECT input after it has been submitted. <script> $(document).ready(function() { //elements var progressbox = $("#progressbox"); var progressbar = $("#progressbar"); var statustxt = ...

Error loading code. Works when manually pasted, but not when executed with JavaScript

After some trial and error, I found that this code works perfectly if I manually copy the content from the class isotope in 1.php to the class grid on this page. However, when I try to use JS to do the same thing, it mysteriously stops working. Any sugge ...

Sending an AJAX request from one subdomain to another subdomain within the same domain

Is it true that cross-domain ajax requests require a 'proxy' server to be used? But what if an ajax request is made from server1.example.com to server2.example within the same domain of example.com? Would that still not work? I've noticed ...

How to dynamically add events to a JQuery FullCalendar using a loop

When utilizing the jQuery full calendar, I need to dynamically set events based on data obtained from a database. To achieve this, I am using data attributes to assign values and then display them on the calendar. Below is an example of my html twig code: ...

Switch between viewing outcomes retrieved from a database

I'm fairly new to working with jQuery, PHP and databases, but I have managed to successfully create a database and retrieve data using PHP. When a search term is entered, the retrieved data from the database is displayed on the results page. For exam ...

Issue found in VS2015 with the sequence of AngularJS TypeScript ts files within the appBundle.js file

I've been diving into AngularJS and TypeScript with the VS2015 RC Cordova TypeScript project. Recently, I created a "MyController.ts" file in the same folder as "index.ts". The code worked perfectly fine: module MyTestApp{ export class MyContro ...

Accessing/Storing Pictures in MongoDB using Mongoose

I've been struggling with managing images in MongoDB for a while now. Everywhere I look suggests using GridFS because of the 16mb size limit per document. However, the documents I want to store are all <16mb this: var ...

What is causing the component to render three times?

Below is the structure of my component: import { useEffect, useState } from "react"; function Counter() { const [count, setCount] = useState(0); console.log("comp run"); const tick = () => { setCount(count + 1); conso ...

Using the HTTP Post method to retrieve a file object: a step-by-step guide

Is there a way to utilize a http POST request in order to retrieve a file object? Though the uploading of files to the server using the POST request seems successful and flawless, attempting to fetch the file results in an unusual response: console output ...

Why does tsc produce a compiled file that throws an exception when executed, while ts-node successfully runs the TypeScript file without any issues?

I have written two ts files to test a decorator. Here is the content of index.ts: import { lockMethod } from './dec'; class Person { walk() { console.info(`I am walking`); } @lockMethod run() { console.info(`I am running`); } ...

What is preventing me from consistently accessing the Type Definition while my cursor is on a JavaScript/TypeScript parameter name in VS Code, and what are some strategies I can use to overcome this issue?

Imagine I have the following code snippet in my VS Code: type T1 = { x: number }; type T2 = { x: number } & { y: string }; function foo(arg1: T1, arg2: T2) {} If I place my cursor on arg1 and go to the type definition (either through the menu or a sh ...

Steps for creating a copy of an Angular component

https://i.stack.imgur.com/4RMsR.png Whenever the user clicks on the Create Copy button, I aim to replicate the content of the DashboardComponent and position the duplicated version below the original one (the DashboardComponent featuring four dark blue sq ...

Resolving unexpected behavior with res.locals and pug integration

I have a function in my app.js that allows the user-id to be accessible in pug templates. app.use(function (req, res, next) { res.locals.currentUser = req.session.userId; next(); }); When logged in, I can access the id. However, when not logged in, t ...

How can I retrieve the document id from Firestore using Angular?

I attempted to generate an auto document ID in Firestore and retrieve the document ID in Angular 8 using the code provided. However, I am encountering an issue where I only receive the document ID after the execution has been completed. Can someone pleas ...

Handling Errors with Async-Await in JavaScript: Struggling to Retrieve Error Specifics from Error Objects

Within my Node Express JS web application, there is a specific function chain present where an API function attempts to call a service function and handle any errors that may be thrown from within the service function. Located in FWBDataExtracService.js c ...