我无法将来自 Web 的嵌套 json 数组映射到我在 Angular2 中的模型数组。假设我有如下 json 数组响应:
[{
"base_url": "http://mysearch.net:8080/",
"date": "2016-11-09",
"lname": "MY PROJ",
"name": "HELLO",
"description": "The Test Project",
"id": 10886789,
"creationDate": null,
"version": "2.9",
"metrics": [{
"val": 11926.0,
"frmt_val": "11,926",
"key": "lines"
},
{
"val": 7893.0,
"frmt_val": "7,893",
"key": "ncloc"
}],
"key": "FFDFGDGDG"
}]
我试图手动映射引用链接 Angular 2 observable doesn't 'map' to model 的字段到我的模型,并能够通过 ngFor 迭代在我的 HTML 中显示那些......但我也想在 HTML 中显示 ncloc 和线值,但我不确定如何将这些值映射到我的模型数组,如在上面的链接中提到。 你能帮我解决这个问题吗?
谢谢。
编辑
模式类
export class DeiInstance {
base_url: string;
date: string;
lname : string;
name : string;
id : number;
key:string;
constructor(obj: DeiInstance) {
this.sonar_url = obj['base_url'];
this.lname = obj['lname'];
this.name = obj['name'];
this.id = obj['id'];
this.key = obj['key'];
this.date = obj['date'];
}
// New static method.
static fromJSONArray(array: Array<DeiInstance>): DeiInstance[] {
return array.map(obj => new DeiInstance(obj));
}
}
最佳答案
您可以大大简化您的模型和映射。 您无需手动映射 API 响应。 JavaScript/TypeScript 可以为您做到这一点。
首先你需要多个接口(interface)。
export interface DeiInstance {
base_url: string;
date: string;
lname: string;
name: string;
description: string;
id: number;
creationDate: string; //probably date
version: string
metrics: Metric[];
key: string;
}
export interface Metric {
val: decimal;
frmt_val: decimal;
key: string;
}
然后您可以使用 as
-TypeScript 的“运算符”将您的 API 响应转换为 DeiInstance 类型。
sealSearch(term: string): Observable<DeiInstance[]> {
return this.http.get(this.sealUrl + term)
.map(response => response.json() as DeiInstance[])
.catch(this.handleError);
}
如果您使用接口(interface)而不是类,您还有一个优势,即发送到客户端浏览器的生产代码更少。 该接口(interface)仅在预编译时存在,或者您可以随意调用它。
希望我的代码能正常工作并解决您的问题。
关于arrays - Angular2 将嵌套的 json 数组映射到模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40967599/