Jojje
Jojje

Reputation: 1779

angular observable http call map response to interface

I have a function that calls a rest api like this:

getProducts(category: string): Observable<IProduct[]> {
    let url = `/rest/getproducts?category=${category}`;
    return this._http.get<IProduct[]>(url);
  }

The response from the service looks like this:

[
  {
    "ProductId": 1,
    "CategoryType": "XC",
    "Name": "Prod A"
  },
  {
    "ProductId": 2,
    "CategoryType": "XY",
    "Name": "Prod B"
  },
]

My model looks like this:

export interface IProduct {
    id: string;
    type: string;
    name: string;
}

Is there a way to map the response to my model in an easy way? Should I use the map function? I know I could change the model to suite the response, but I would rather like to squeeze the response into my model (the example is simplified).

Upvotes: 5

Views: 12025

Answers (2)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249476

The simplest solution would be to use an interface that is the shape of the actual data from the server. Less headache, no mapping, less maintenance.

Even if you want to do some mapping it would still be a good idea to have an interface for the server object, so mapping can be done safely:

interface IServerProduct {
    "ProductId": number;
    "CategoryType": string;
    "Name": string;
}

export interface IProduct {
    id: string;
    type: string;
    name: string;
}

getProducts(category: string): Observable<IProduct[]> {
    let url = `/rest/getproducts?category=${category}`;
    return this._http.get<IServerProduct[]>(url).pipe(
        map(o => o.map((sp): IProduct => ({ // IProduct specified here ensures we get excess property checks
            id: sp.ProductId + '', // number in server interface, map to string 
            name: sp.Name,
            type: sp.CategoryType,
            typeMisaken: sp.CategoryType, // error here
        })))
    );
}

Upvotes: 6

Sajeetharan
Sajeetharan

Reputation: 222532

Your interface should look like the below, if you do not want to do any changes to code, you could check it here json2ts

declare module namespace {
    export interface IProduct {
        ProductId: number;
        CategoryType: string;
        Name: string;
    }
}

otherwise you could use the array.map function and generate your array on own.

Upvotes: 3

Related Questions