Angularjs 对接口的角度可观察http调用映射响应
我有一个调用rest api的函数,如下所示:Angularjs 对接口的角度可观察http调用映射响应,angularjs,typescript,Angularjs,Typescript,我有一个调用rest api的函数,如下所示: getProducts(category: string): Observable<IProduct[]> { let url = `/rest/getproducts?category=${category}`; return this._http.get<IProduct[]>(url); } [ { "ProductId": 1, "CategoryType": "XC",
getProducts(category: string): Observable<IProduct[]> {
let url = `/rest/getproducts?category=${category}`;
return this._http.get<IProduct[]>(url);
}
[
{
"ProductId": 1,
"CategoryType": "XC",
"Name": "Prod A"
},
{
"ProductId": 2,
"CategoryType": "XY",
"Name": "Prod B"
},
]
export interface IProduct {
id: string;
type: string;
name: string;
}
我的模型如下所示:
getProducts(category: string): Observable<IProduct[]> {
let url = `/rest/getproducts?category=${category}`;
return this._http.get<IProduct[]>(url);
}
[
{
"ProductId": 1,
"CategoryType": "XC",
"Name": "Prod A"
},
{
"ProductId": 2,
"CategoryType": "XY",
"Name": "Prod B"
},
]
export interface IProduct {
id: string;
type: string;
name: string;
}
有没有一种方法可以简单地将响应映射到我的模型?我应该使用地图功能吗?我知道我可以更改模型以适应响应,但我更希望将响应压缩到我的模型中(示例已简化)。您的界面应如下所示,如果您不想对代码进行任何更改,可以在此处检查
declare module namespace {
export interface IProduct {
ProductId: number;
CategoryType: string;
Name: string;
}
}
否则,您可以使用array.map函数自己生成数组。最简单的解决方案是使用一个界面,该界面是来自服务器的实际数据的形状。头痛更少,无需映射,维护更少 即使要进行一些映射,最好还是为服务器对象提供一个接口,这样映射就可以安全地完成:
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
})))
);
}
接口产品{
“ProductId”:编号;
“CategoryType”:字符串;
“名称”:字符串;
}
导出接口IPProduct{
id:字符串;
类型:字符串;
名称:字符串;
}
getProducts(类别:字符串):可观察{
让url=`/rest/getproducts?category=${category}`;
返回此。\u http.get(url.pipe)(
map(o=>o.map((sp):IProduct=>({//IProduct在这里指定确保我们得到多余的属性检查
id:sp.ProductId+'',//服务器接口中的编号,映射到字符串
名称:sp.名称,
类型:sp.CategoryType,
typeMisaken:sp.CategoryType,//此处出错
})))
);
}
如果需要更改属性的名称,则需要手动进行映射。可以做到这一点的库可能也存在:)谢谢您的示例。但我收到一个错误:错误TS2552:找不到名称“map”。你是说“Map”吗?@Jojje有两个Map调用,一个是应该在那里的数组Map,另一个是rxjs Map。您需要从rx运营商处导入它才能工作。你用的是什么版本的angular?我用的是angular5@Jojje这应该是导入,我目前没有5个可用的,但是在7上它是从'rxjs/operators'导入的import{map}代码>