简体   繁体   English

角度可观察的http调用图对接口的响应

[英]angular observable http call map response to interface

I have a function that calls a rest api like this: 我有一个像这样调用rest api的函数:

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). 我知道我可以更改模型以适合响应,但是我想将响应压缩到我的模型中(该示例已简化)。

Your interface should look like the below, if you do not want to do any changes to code, you could check it here json2ts 您的界面应如下所示,如果您不想对代码进行任何更改,可以在此处检查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. 否则,您可以使用array.map函数并自行生成数组。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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