Converting data received from the server into a typescript type within an Angular Service

Received an array of Event type from the server.

public int Id { get; set; }
public string Name { get; set; }
public DateTime Start { get; set; }
public DateTime End { get; set; }

For Angular and TypeScript, I need to transform it into the following class due to multiple pickers in the UI:

  id: number;
  name: string;
  startDate: Date;
  startTime: Date;
  endDate: Date;
  endDatetime: Date;

I am looking for a way to customize the mapping in my event.service.ts before subscribing to it in my component. How can this be achieved?

  getEvents(): Observable<Event[]> {
    return this.http.get<Event[]>(this.eventsUrl);
  }

Answer №1

Considering how to transform the data is crucial, so I will provide an example:

[{
    id: 1,
    name: "John"
}]

Data model implementation using Angular:

export class Person {
    public id: Number;
    public name: string;
    public idName: string;
}

Here's the code for the service:

getEvents(): Observable<Event[]> {
    return this.http.get<any[]>(this.eventsUrl).map<any[], Person[]>(o => {
        let result = [];
        for (let item of o) {
            let p: Person = {
                id: item.id,
                name: item.name,
                idName: item.id + ": " + item.name
            };
            result.push(p);
        }
        return result;
    });
}

This snippet hasn't been tested yet, but it serves as a demonstration of potential data manipulation.

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

Leverage a provider implementation within another implementation of the same provider in Angular

Is it possible to inject one provider implementation into another implementation of the same provider in Angular? I have been unable to achieve this so far. The goal is to be able to customize the second implementation using data from the first implementat ...

Input box in Angular matDatepicker fails when typing due to locale settings

When using a datepicker like this: <mat-form-field> <input matInput [matDatepicker]="picker" placeholder="Choose a date"> <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle> <mat-datepicker #picker> ...

Transferring client-side data through server functions in Next.js version 14

I am working on a sample Next.js application that includes a form for submitting usernames to the server using server actions. In addition to the username, I also need to send the timestamp of the form submission. To achieve this, I set up a hidden input f ...

The component is not being activated by the subject subscribe

I'm having trouble subscribing to the Subject folder_id in the board component when passing the id from the files component. The boardId function is called when a button is pressed in the files component. The activateId is retrieved from the URL snap ...

Encountering a hiccup during the installation process of Angular CLI

I'm encountering an issue in the command line, seeking assistance C:\Users\admin>npm -v 6.9.0 C:\Users\admin>npm install -g @angular/cli npm ERR! Unexpected end of JSON input while parsing near '...vkit/core":"8.0.4", ...

After unsubscribing from RxJS timer, it starts again

Trying out a simple reflex-testing game here. The player has to click on the red rectangle when it turns green, and their score is displayed. However, the issue is that the timer restarts after clicking on the rectangle even though I tried using 'unsu ...

I require clarity on this befuddling syntax that feels like descending into

I came across this example in the official documentation at https://angular.io/guide/form-validation#custom-validators return (control: AbstractControl): {[key: string]: any} => { const forbidden = nameRe.test(control.value); return forbidden ...

How can I use regex within a pipe to split a string in Angular 4?

I need to implement a method where I can split a string based on special characters and spaces in the given regex format, excluding "_". Example: #abc_xyz defgh // output #abc_xyz Example: #abc@xyz defgh // output #abc Example: #abc%xyz&defgh // out ...

Adding dynamic row values to a bootstrap table in angular 4 - what's the best approach?

When using an Angular 4 bootstrap table, I am encountering an issue where only the first row value is displayed in the table from the backend when entering a product in the text box and pressing enter. Even though the alert window shows the data for the se ...

Exploring the power of TypeScript for authenticating sessions with NextJS

Utilizing next-auth's getSession function in API routes looks something like this for me: const mySession = await getSession({ req }); I have confirmed that the type of the mySession is outlined as follows: type SessionType = { user: { email: s ...

Transferring data from the server to the client side in Next JS with the help of getInitialProps

I am currently developing an application using nextJS. Within server/index.ts, I have the following code: expressApp.get('/', (req: express.Request, res: express.Response) => { const parsedUrl = parse(req.url, true); const { query } = ...

Handling Click and Mouse Events with React [react-sortable-hoc, material-ui, react-virtualized]

I have come across an interesting example that I would like to share with you. Check out this live working example on Stackblitz When the delete button on the red bin icon is pressed, the onClick event handler does not get triggered (sorting happens inst ...

using props as arguments for graphql mutation in react applications

Here is the structure of my code: interface MutationProps{ username: any, Mutation: any } const UseCustomMutation: React.FC<MutationProps> = (props: MutationProps) => { const [myFunction, {data, error}] = useMutation(props.Mutati ...

Easily retrieve the value of a form control when it is changed with Form

Currently, I am in the process of reviewing Formly. In my initial attempt, I am trying to trigger a method when the content of a textarea changes. The code snippet below shows what I have tried so far. Unfortunately, it seems like the functionality is no ...

Move the monitoring role from the server to the client side

I am trying to transfer an observer from my server to the client in order to subscribe to it. @SubscribeMessage('createTodo') public handleCreateTodo( @MessageBody() data: IDataForCreateTodo, @ConnectedSocket() client: S ...

Sorting the material table based on the column IDs, which usually correspond to the column names, may not align with the properties of the data

.ts this.displayedColumns = [ { key: 'id', header: '#' }, { key: 'fullname', header: 'Full name' }, { key: 'email', header: 'email' }, { key: 'roleName', header: ...

What is the best way to add JSX to the DOM using React?

Looking to make an addition to my DOM. let parent = document.getElementById("TabContainer"); let settings = <Box id="test"> <GlobalSettings activeTab={"test"}></GlobalSettings> </Box> ...

Verify Angular Reactive Form by clicking the button

Currently, I have a form set up using the FormBuilder to create it. However, my main concern is ensuring that validation only occurs upon clicking the button. Here is an excerpt of the HTML code: <input id="user-name" name="userName" ...

Even when I try to access the properties of the arguments object, it remains empty and has a zero

Why is the arguments object showing a length of zero when I pass parameters to the function, even though I can still access its properties? I am referring to the arguments object that is implemented by all JavaScript functions, allowing you to access the f ...

When attempting to utilize class validators in NestJS, Param is refusing to cast to DTO type

I'm currently working on implementing validation for the parameter I receive in a request, especially when trying to delete something. The parameter is expected to be a string but it must adhere to the format of a valid UUID. To achieve this, I have i ...