The traditional Angular model definition has been revamped with the implementation of web services model

I have a TypeScript model that looks like this:

import * as moment from 'moment';

export class Activity {
  public id: number;      
  public activityDate: string;      
  public day: number = moment(this.activityDate).dayOfYear();
}

Also, a C# model is sent by WebApi in this format:

public class Activity
{     
    [JsonProperty("id")]
    public int Id { get; set; }

    [JsonProperty("activityDate")]
    public DateTime ActivityDate { get; set; }
}

There is a mapping using a simple response.json() in my service class.

My concern is that the property day disappears from my model.ts.

Is there a way to declare something to maintain integrity in the TypeScript model? Or any binding on model retrieval keep the structure intact?

Answer №1

In order to map the response.json() call, you must explicitly define the day property as it will not be calculated automatically. Here is a suggestion to achieve this:

export interface Activity {
  id: number;
  activityDate: string;
  day?: number;
}
export const mapActivityFromServer(d => ({
  ...d,
  day: moment(d.activityDate).dayOfYear()
}));

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

Enter data into a form control to update the browser URL

I have a table in my Angular application with search boxes above the header. When users enter values into these search boxes, the corresponding column in the table gets filtered. My goal is to update the URL directly with the values entered in the search ...

Employing square bracket notation based on the input data

I'm currently in the process of enhancing some code within my library, but I've encountered a perplexing issue with bracket notation not functioning as expected when attempting to call an imported class. The parameter type expects a camelCased s ...

Mastering the incorporation of Context in React with Typescript

I am currently in the process of setting up a context provider for my Next.js application using TypeScript. Although I have previously set up a context provider in React using plain JavaScript, this time I am delving into learning TypeScript. In the code ...

Tips for customizing colors for dynamically added bars in an Angular bar chart

Here is a sample of my chart: Check out the chart By clicking the change data button, I am adding a new bar to the chart. Is there a way to change only the color of the newly added bar? Is it possible to achieve this? ...

TypeScript/Javascript - Error: The specified function is not callable

After recently delving into TypeScript, I found myself encountering an error in my code for a wheel mini-game on my app. The specific error being displayed in the console is: this.easeOut is not a function The relevant portion of the code causing the iss ...

Is Axios the sole option for API calls when utilizing Next.js with SSG and SSR?

Can someone clarify the best practice for data fetching in Next.js? Should we avoid using axios or other methods in our functional components, and instead rely on SSG/SSR functions? I'm new to Next.js and seeking guidance. ...

Using the up and down arrow keys on the keyboard to navigate through a mat-form-field-infix field in

Is there a way to simulate keyboard inputs for the up and down buttons in a drop-down list while working with mat-form-field-infix? I attempted using Robot framework, but it seems that the drop-down list does not appear unless I manually interact with it ...

Tips for bringing in an enum from TypeScript?

I am working with a module defined in TypeScript that looks like this: declare module MyTypes { export enum MyEnum { GOOD = 'Good', BAD = 'Bad', UNKNOWN = '-' } export interface MyType1 { ...

Having trouble getting @types/express-session to function properly. Any suggestions on how to fix it?

My web-app backend is built with TypeScript and I've integrated express-session. Despite having @types/express and @types/express-session, I continue to encounter type errors that say: Property 'session' does not exist on type 'Request ...

Troubleshooting TypeScript errors in a personalized Material UI 5 theme

In our codebase, we utilize a palette.ts file to store all color properties within the palette variable. This file is then imported into themeProvider.tsx and used accordingly. However, we are encountering a typescript error related to custom properties as ...

Ensure that the interface limits the key value to match precisely the value of a constant in Typescript

Seeking assistance in understanding how to enforce a specific type for an optional key within an interface: const FIRST = "FIRST" const SECOND = "SECOND" interface TSomeInterface { element: Element order?: typeof FIRST | typeof ...

Encountering a 403 error with RXJS when attempting to subscribe to a websocket in Angular

I am currently searching for a resolution to this issue without making any upgrades to Angular or its dependencies, as it could potentially impact other parts of the code base https://i.sstatic.net/Jeb55.png package.json { "name": "angular4", "v ...

What is the best approach for setting up a global pipe that can be utilized across various modules?

One of my Angular projects includes a custom pipe called CurrConvertPipe. import {Pipe, PipeTransform} from '@angular/core'; import {LocalStorageService} from './local-storage'; @Pipe({name: 'currConvert', pure: false}) expor ...

difficulties arise when trying to use ngOnChanges to update an array

My code includes an array that is being updated from another component, with new Strings being added to it using the array.push() method. I have verified this update by testing it with a button, however, ngOnChanges does not seem to detect any change in ...

Hold off on utilizing information from a single observable until a later time

In my Angular component, I am working with the following code: @Component({...}) export class ComponentOne implements OnDestroy, OnChanges { readonly myBehaviourSub = new BehaviorSubject<Observable<MY_CUSTOM_INTERFACE>>(NEVER); constructo ...

implementing an event listener in vanilla JavaScript with TypeScript

Can anyone help me figure out how to correctly type my event listener in TypeScript + Vanilla JS so that it has access to target.value? I tried using MouseEvent and HTMLButtonElement, but I haven't been successful. const Database = { createDataKeys ...

Ways to broaden the type signature of a Typescript comparator in order to facilitate sorting by properties nested within objects?

Here is a function that I created: arr.sort(alphabeticallyBy("name")) The function has the following signature: <T extends string>(prop: T) => (a: Partial<Record<T, string>>, b: Partial<Record<T, string>>) => ...

What is the best way to transform this JSON data into an array of key-value pairs in JavaScript?

Dealing with nested JSON data can be challenging, especially when trying to extract key-value pairs efficiently. If anyone has suggestions on how to simplify this process and improve readability, please share your insights. The goal is to transform the ne ...

The UI elements are failing to reflect the changes in the data

In an attempt to establish communication between three components on a webpage using a data service, I have a Create/Edit component for adding events, a "next events" component for accepting/declining events, and a Calendar component for displaying upcomin ...

Retrieving Data from Vuetify Component within vue 3

Currently, I am in the process of creating my own wrapper for Vuetify components to eliminate the need to repeatedly define the same props in each component. For example, I aim to develop a custom TextField with defaultProps while still being able to accep ...