"Utilizing TypeScript to retrieve an object with a specified date data type

I am working with a Python REST API and Angular 2 on the frontend. I am facing an issue with parsing GET request responses into objects Answer with date type field. Here is an example of my json:

{
"date_answer": "2015/07/05", 
"id": 1, 
"text": "some text", 

}

Currently, I have this code in my controller:

getAnswers() : Observable<Answer[]> {
return this.http.get(this.answerUrl)
          .map((res:Response) => res.json())
          .catch((error:any) => Observable.throw(error.json().error || 'Server error'));}

I have tried to address this issue by parsing the Date field in the constructor as shown below:

 export class Answer {
  id: number;
  text: string;
  date_answer: Date;

  constructor(
    id: number, 
    text: string, 
    date_string: string
    ){
      this.date_answer = new Date(date_string)
    }
}

However, this approach has not been successful. I am wondering if there might be a better way to extract the date from the JSON response as a Date type.

Answer №1

I have implemented parsing functionality using the powerful library called class-transformer created by pleerock.

You might find it beneficial to explore this tool for your own projects as well.

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

Dealing with a null array triggering the error message "Uncaught (in promise) SyntaxError: Unexpected end of JSON input."

My react / redux / node express app is designed to manage patient information, but I'm facing a bug when trying to read new data after deleting a patient encounter. Everything works smoothly until the last encounter associated with the patient is dele ...

Where can I find bogus JSON APIs specifically designed for retail or ecommerce purposes?

Looking for a site that offers fake JSON data containing an array of objects related to stores, including images, prices, and names. I want to enhance my skills in working with JSON Rest APIs using GET and POST requests. Any recommendations other than a ...

The html wrapping around the jQuery JSON Response adds an extra layer of presentation

Seeking JSON data for an autocomplete function, but running into a problem because the JSON is wrapped in an HTML span tag. This issue stems from a VB backend library that won't be updated anytime soon. I need to find a way to remove the span tag from ...

Every time I try to install a particular version of angular using angular cli, it seems to result in the incorrect version

_ _ ____ _ ___ / \ _ __ __ _ _ _| | __ _ _ __ / ___| | |_ _| / △ \ | '_ \ / _` | | | | |/ _` | '__| | | | | | | / ___ \| | | | (_| | |_| | | (_| | | | ...

ManagedZone instance not found

I recently incorporated a new button into my application <material-button raised #dialog.show()>Show Dialog</material-button> However, upon implementation, I encountered the following error: Observatory listening at http://127.0.0.1:46411/ & ...

Guide on implementing Regular Expressions in Directives for validation in Angular 8

Managing 8 different angular applications poses its unique challenges. In one of the applications, there is a directive specifically designed for validating YouTube and Vimeo URLs using regular expressions. Unfortunately, once the RegExp is declared, ther ...

Decoding an inserted JSON object in Android application

Apologies for any language barrier. I am attempting to parse the inserted JSON data, using the following example: { "myTable": { "1": { "type": "1", "category": "1", "body": { "2": { ...

What is the process of converting an Array that is nested within an Object?

I am facing compile errors while attempting to convert an Object containing an Array of Objects. Here is the initial structure: export interface CourseRaw { metaInfo: MetaInfoRaw; gameCode: number; gameText: string; images?: ImageRaw[]; // Having ...

Get JSON or partial HTML responses from ASP.NET MVC controller actions

Is there a recommended method for creating controller actions that can return either JSON or partial HTML based on a specified parameter? I'm looking for the optimal way to asynchronously retrieve the results in an MVC page. ...

Join queries together to create organized data output

Here is a JSON input example to consider: [ { "category": "fruit", "item1": "apple", "item2": "orange" }, { "category": "fruit", ...

Decoding a JSON array literal in Swift 3

One of my PHP scripts is designed to provide a JSON response in the form of an array literal. This is what the response looks like: ["coffee_shop","library"] However, when I attempt to parse this data in Swift after successfully receiving it, I encounte ...

Ways to troubleshoot opencv.js generating random values when applying cv.threshold

Whenever I choose an image and use cv.threshold, it outputs a strange number 6620912 The number seems to change at times https://i.sstatic.net/Tp9LP.png 6620912 Promise.catch (async) (anonymous) @ App.tsx:49 commitHookEffectListMount @ react-dom_client ...

Texture Elusion not being rendered

I'm experiencing difficulties with rendering items in my Forge mods. The error message I am encountering is as follows: [16:14:07] [Client thread/ERROR] [FML]: An exception occurred while loading the model for variant "skycastle:itemskygem#inventor ...

include the ReactToastify.css file in your project using the import statement

Error in file path C:\Users\User\Documents\GitHub\zampliasurveys_frontend\node_modules\react-toastify\dist\ReactToastify.css:1 ({"Object.":function(module,exports,require,__dirname,__filename,jest){:ro ...

Tips for resolving the error message "What to do when reportWebVitals can't be located

Having some trouble with importing reportWebVitals for my React 18 application that is based on WebPack 5. Below is a snippet of my index.tsx file: import React from 'react'; import ReactDOM from 'react-dom/client'; import './style ...

Ensure that the key and value types in a Typescript Map are strictly specified

Is it feasible to generate a map that consists of key-value pairs, where the key is represented by a string and the value corresponds to an object containing specific properties defined by mapValue? type mapValue { first: string; second: boolean; } Yo ...

Suggestions for the structure of log information in the REST api format

Looking for a solution that can handle log data efficiently? Imagine having an api like logs?from=1/1/15 that returns all log lines from a specific date, but the problem is dealing with potentially massive amounts of data. Parsing it to a DOM using xml/jso ...

Do you believe this problem with transpilation has been properly reported to babel-jest?

I recently encountered a problem in the jest project regarding babel-jest transpilation. I added some code that appeared to be error-free, but caused transpilation to fail completely. Although the issue seemed related to a Typescript Next project, there a ...

Is there a way for me to store the current router in a state for later use

I am currently working on implementing conditional styling with 2 different headers. My goal is to save the current router page into a state. Here's my code snippet: const [page, setPage] = useState("black"); const data = { page, setPage, ...

Running out of memory due to inefficient mark-compacting processes nearing the heap limit in Angular 8 allocation

A significant portion of the modules are built, with only one active in progress. The process is located at ...\src\index.js??extracted!D:\Clients\app\node_modules\sass-loader\lib\loader.js??ref--15-3!D:\src&bso ...