问题描述
我无法将嵌套的json数组(从Web响应)映射到Angular2中的模型数组.假设我有如下的json数组响应:
I am not able to map the nested json array which is response from Web to my model array in Angular2. Suppose I have json array response as below:
[{
"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不会映射"到模型到我的模型,并且能够通过遍历ngFor ......在我的HTML中显示这些内容,但是我也想在HTML中也显示ncloc和lines值但是我不确定如何将这些值映射到我的Model数组中,如上面的链接中所述.你能帮我吗?
I was trying to manually map the fields referring the link Angular 2 observable doesn't 'map' to model to my model and was able to display those in my HTML by iterating through ngFor.....but I want to also display ncloc and lines value also in the HTML but I am not sure how to map those values to my Model array like mentioned in the above link.Can you please help me with this?
谢谢.
编辑
模式类
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可以为您做到这一点.
You can simplify your model and your mapping a lot.You don't need to map your API response manually. JavaScript/TypeScript can do this for you.
首先,您需要多个接口.
First you need multiple interfaces.
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;
}
然后,您可以使用 TypeScript 的as
-运算符"将您的API响应转换为DeiInstance类型.
You can then use the as
-"operator" of TypeScript to cast your API response to the DeiInstance Type.
sealSearch(term: string): Observable<DeiInstance[]> {
return this.http.get(this.sealUrl + term)
.map(response => response.json() as DeiInstance[])
.catch(this.handleError);
}
如果使用接口而不是类,则还具有以下优点:可以将更少的生产代码发送到客户端浏览器.该接口仅在预编译时存在,或者您想调用它.
If you use interfaces instead of classes you have also the advantage that you have less production code which will be sended to the client browser.The interface is only there for pre-compile-time or however you want to call it.
希望我的代码有效,并且可以解决您的问题.
Hope my code works and it solves your problem.
这篇关于Angular2将嵌套的json数组映射到模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!