Blake Rivell
Blake Rivell

Reputation: 13875

Mapping what is returned from the server to an typescript type in an Angular Service

I am receiving an array of type Event from the server.

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

In Angular and TypeScript I need to convert to the following class since I have 4 separate pickers in the UI (2 date pickers, 2 time pickers):

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

How can I change the following in my event.service.ts to do this mapping with custom code then allow my component to simply subscribe to it?

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

Upvotes: 1

Views: 177

Answers (1)

ProgrammingLlama
ProgrammingLlama

Reputation: 38727

I don't know how you plan to mutate your data, so I'll give my own example:

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

Data model (Angular):

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

Service code:

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;
    });
}

I've not tested it, but something like this will manipulate the data returned.

Upvotes: 1

Related Questions