简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM