Search code examples
angularangular-httpclient

Mapping json object to interface with HttpClient


I'm having some problem understanding how I can transform my json response to fit my interface for a multiselect.

Here's the response that I'm getting from the api:

[
  {
    "TransportTypeId": 1,
    "Code": "RT  ",
    "Name": "Round Trip          "
  },
  {
    "TransportTypeId": 2,
    "Code": "N/A       ",
    "Name": "UnAllocated         "
  },
  {
    "TransportTypeId": 3,
    "Code": "OWOut     ",
    "Name": "OneWay Out          "
  },
  {
    "TransportTypeId": 4,
    "Code": "OWHome    ",
    "Name": "OneWay Home         "
  }
]

This is the interface that I'm trying to map it to:

export interface IMultiSelectOption {
    id: any;
    name: string;
    isLabel?: boolean;
    parentId?: any;
    params?: any;
    classes?: string;
}

I would like to map TransportTypeId to id and Name to name.

As I said I'm using the new HttpClient in angular 4 and I'm having some difficulties finding any example like this.

this is my get function:

getTransportTypes(): Observable<TransportType> {
    let options: TransportType;
    let multiselect: IMultiSelectOption
    let requestUri = '/BaseData/TransportTypes';
    debugger;
    return this.http.get<TransportType>(`${this.flighttransportcapacityUrl}${requestUri}`)
}

This is returning the response and mapping it to TransportType that is exactly the same as the response properties:

export class TransportType{
    TransportTypeId: number;
    Code: string;
    Name: string;
}

This is working correctly but I was thinking there should be some easier way of converting the response to IMultiSelectOption then to loop over the result of the get function?

Including my dirty way of doing it.

    this.base.getTransportTypes().map(item => this.convertToMultiSelect(item)).subscribe(options => this.transportOptions = options)

and the convertfunction:

convertToMultiSelect(item: any): IMultiSelectOption[] {
    debugger;
    let v = item;

    let options = [];

    for (var i = 0; i < item.length; i++) {

        options.push({ id: item[i].TransportTypeId, name: item[i].Name})
    }

    return options;
}

Solution

  • When you want to convert a list of objects to a new list of the same size, use the map() method. So the code could look like this:

    this.base.getTransportTypes()
      .map(transportTypes => transportTypes
        .map(trType => ({ id: trType.TransportTypeId, name: trType.Name }))
      )
      .subscribe(options => this.transportOptions = options)
    

    Or if you want to keep the convertToMultiSelect method:

    convertToMultiSelect(items: TransportType[]): IMultiSelectOption[] {
      return items.map(item => ({ id: item.TransportTypeId, name: item.Name }));
    }