Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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).

like image 258
Jojje Avatar asked Jan 26 '19 11:01

Jojje


2 Answers

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
        })))
    );
}
like image 194
Titian Cernicova-Dragomir Avatar answered Nov 15 '22 04:11

Titian Cernicova-Dragomir


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.

like image 38
Sajeetharan Avatar answered Nov 15 '22 04:11

Sajeetharan