Transform JSON into a TypeScript interface with a specialized Date method

Within my Angular 7 project, there is a Post Model defined as follows:

export interface PostModel {
  id: number;
  created: Date;
  published: boolean;
  title: string; 
}

I have implemented an Angular service method aimed at retrieving posts:

public getPosts(): Observable<PostModel[]> {

  return this.httpClient.get<PostModel[]>(url).pipe(

    map((post: PostModel)) => {

      return {
        id: post.id, 
        created: new Date(post.created),
        published: post.published,
        title: post.title
      };

    })

  };

In the process of converting the API response to PostModel, I discovered that the conversion for the created type to Date does not happen automatically in Angular.

Desiring reusability for the mapping code across various sections of my application, I attempted:

map((post: PostModel)) => return mapPostFromJson(post));

Even though I could convert PostModel to a class and implement mapPostFromJson as its method, I am inclined to retain PostModel as an interface.

The challenge lies in creating the mapPostFromJson method. My attempt looked like this:

mapPostFromJson(data: any) : PostModel {

  return map((post: PostModel) => {

    return { 
      id: post.id, 
      created: new Date(post.created),
      published: post.published,
      title: post.title
    };

  });

}

However, this function fails to compile. I am uncertain about how to utilize map outside of the pipe...

Answer №1

It seems there might be some confusion in understanding your question, but would the mapping function mentioned work for you?

mapPostFromJson(data: any): PostModel {
    return { 
        id: data.id, 
        created: new Date(data.created),
        published: data.published,
        title: data.title
    };
}

If not, you could consider a more generic approach using functional principles by defining general functions that can be reused to create your mappers:

// This function takes a structure of functions and applies them to data, returning a result structure
const mapper = functions => json => Object.entries(json)
    .map(([k, val]) => ({ [k]: (functions[k] || (x => x))(val) }))
    .reduce((acc, o) => Object.assign(acc, o), { });

You can then easily create a mapper and apply it to your JSON data:

// Create a mapper that passes all properties
// while transforming 'created' to a date
const mapPostFromJson = mapper({
    created: x => new Date(x)
});

const post = mapPostFromJson(jsonPost);

With this mapper, all JSON properties will be passed through, except the 'created' field which will be transformed into a date.

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 TypeScript package encountered an unexpected token export

I have integrated a module from a private git repository. Package.json: "my-module": "git+https://username:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cebeb98eaca7baacbbada5abbae0a1bca9">[email protected]</a> ...

Bringing in TypeScript declarations for the compiled JavaScript librarybundle

I have a custom library written in TypeScript with multiple files and an index.ts file that handles all the exports. To consolidate the library, I used webpack to compile it into a single index.js file but now I'm facing challenges importing it with ...

Having trouble receiving a response from the websocket using RxJS in Node.js with Angular

Currently experimenting with setting up a WebSocket using rxjs webSocket I have managed to create a node server without any errors, but it is not sending messages to the server or connected users When I switch to 'ws://echo.websocket.org/', I c ...

What could be the reason for ngOnChanges lifecycle hook not getting invoked?

I am currently experimenting with Angular 2 in an effort to learn more about it. I noticed that ngOnChanges is not triggering in the code below: app.component.ts: import { Component, Input } from "@angular/core" import { FormsModule } from '@angular ...

Ionic 3 is unable to find a provider for CallNumber

Recently, I have been working with Ionic 3 and encountered an issue when trying to call a number using the Call Number plugin. Here are the steps I followed to add the plugin: ionic cordova plugin add call-number npm install --save @ionic-native/call-numb ...

Implementing data binding for arrays of inputs in Angular

Can anyone provide assistance with this code snippet and explain why it is not functioning as expected? I am trying to generate input fields from a string array and bind each input value to its corresponding element in the array. It seems like a common tas ...

Using a snippet of HTML code from one Angular component in another component

Is it possible to use a specific div element from one Angular component in another component? main component.html <html> <div1> some elements </div1> <div2> some elements </div2> In the child ...

Ways to retrieve the most recent value from an Angular 4 subscription

What is the best way to retrieve the most recent value from a subscribe method in Angular 4? this.AbcSrvice.value.subscribe(data => {console.log(data)}) ...

`Is there a way to implement a collapsing toolbar in Ionic 3?`

I am looking to design a page similar to the one shown above. The layout includes an image positioned at the top of two divisions, or sandwiched between a toolbar and content as seen in the image above. I have been unable to find any resources or documen ...

Adding elements from one array to another array of a different type while also including an additional element (JavaScript/TypeScript)

I'm having trouble manipulating arrays of different types, specifically when working with interfaces. It's a simple issue, but I could use some help. Here are the two interfaces I'm using: export interface Group { gId: number; gName: st ...

Web performance issues noticed with Angular 8 and Webpack 3.7 rendering speed

My web application is currently taking 35 seconds to render or at least 1.15 seconds from the initial Webpack start. I've made efforts to optimize Webpack, which has improved the launch speed, but the majority of time is consumed after loading main.j ...

Is it possible to begin utilizing Angular 2 without requiring Node?

I am interested in experimenting with using angular 2 for VS 2015, however, the first requirement is having node.js. To my understanding, do I need node.js as a web server and npm to download packages? Is it possible to achieve the same goal using IIS an ...

Ways to update a component upon becoming visible in Angular

Within my Angular 4.3.0 project, the header, left panel, and right panels are initially hidden on the login page until a successful login occurs. However, once they become visible, the data is not pre-loaded properly causing errors due to the ngOnInit meth ...

Validation with zod is unsuccessful under certain conditions

I am facing an issue with my form that contains a radio button with three input fields inside it. The submit button is supposed to validate that only one of the input fields is correctly entered. Despite using refine() in zod validation, I cannot get it ...

Angular 4 Filtering Pipe: Simplify Data Filtering in Angular

Attempting to replicate AngularJS's OrderBy feature. Working with an array like this, I am aiming to filter the cars by their car category. [ { "car_category": 3, "name": "Fusion", "year": "2010" }, { "car_category": 2, "na ...

The TypeScript error states that the argument type 'string | undefined' cannot be assigned to the parameter type 'string'

Receiving TS error that says "Object is undefined" I am attempting to retrieve the "userid" from my headers. However, I keep encountering the error message "Argument of type 'string | undefined' is not assignable to parameter of type 'str ...

Issue with Typescript and react-create-app integration using Express

I'm relatively new to Typescript and I decided to kickstart a project using create-react-app. However, I encountered an issue while trying to connect my project to a server using express. After creating a folder named src/server/server.ts, React auto ...

Having trouble with my React component timer not functioning properly

How can I utilize the Header Component as a Clock timer for my webpage to update every second? Despite searching on Google, I couldn't find examples that match my requirements. Why is the tick() function not functioning properly even though there are ...

Consequences of eliminating Angular component wrapper tags from the DOM

Imagine there is a component named <hello-world> with the following HTML template: <div>Hello World!</div> When this component is used and inspected in the DOM, it shows up like this: <hello-world> <div>Hello World!</div ...

Solving CORS policy error in a MEAN stack application deployed on Heroku

I've been grappling with a CORS policy error in my MEAN stack app for quite some time now. The specific error message I keep encountering is: "Access to XMLHTTPRequest at <my heroku app url.com/login> from origin has been blocked by CORS ...