我已经尝试了很多,但无法将端点响应映射到我的模型。我正在使用 HttpClient 和 Angular4。
我从服务中获取了数据,但它没有正确映射到我的模型类。
我有以下 JSON 服务正在返回:
{
"result": [
{
"id": "1",
"type": "User",
"contactinfo": {
"zipcode": 1111,
"name": "username"
}
}
]
}
我在打字稿中创建了一个模型,我想将其映射到 json 响应:
export interface result {
zipcode: number;
name: string;
}
这就是我调用 JSON 端点的方式。
result : string[] = [];
constructor(private http: HttpClient) { }
public getList(): result[] {
this.http.get<result[]>('url...', { headers: this.headers }).subscribe(
data => {
// 1. Data is returned - Working
console.log('data: ' + data);
this.result= data;
// This is the problem. My data is not mapped to my model. If I do following a null is returned
console.log('data mapped: ' + this.result[0].name);
},
(err: HttpErrorResponse) => {
// log error
}
);
return this.result;
}
您需要在组件中导入接口,
import { result } from '.result';
你的界面应该看起来像,
interface RootObject {
result: Result[];
}
interface Result {
id: string;
type: string;
contactinfo: Contactinfo;
}
interface Contactinfo {
zipcode: number;
name: string;
}
并将结果类型更改为,
result : result;
并将结果指定为,
this.result = data;
您可以使用http://www.jsontots.com/ http://www.jsontots.com/创建基于JSON的接口
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)