我的数据来自web api,如下所示。如何将产品阵列映射到产品中,我这样做的原因是我需要将eating_time转换为javascript datetime。
我的代码,其中this.products = product的类只会存储数组和产品列表。
//来自API的数据
[ {datetime: "2017-06-25T07:45:00+08:00", name: "Apple", unit: 1, product: [{eating_time: "2017-06-25T07:45:00+08:00", qtytaken: 1, chart_bar=1 },
{eating_time: "2017-06-25T17:45:00+08:00", qtytaken: 1, chart_bar=1 },
{eating_time: "2017-06-25T23:55:00+08:00", qtytaken: 1, chart_bar=1 } ]
]
// Class
class Product {
eating_time: Date;
qtytaken: number;
chart_bar = 1;
constructor({eating_time, qtytaken, chart_bar }) {
this.eating_time = new Date(eating_time);
this.qtytaken = dosage;
this.chart_bar = chart_bar;
}
}
export class ProductTaken {
datetime: Date;
name: string;
unit: number;
products: Product[];
constructor({datetime, name, unit, product} ) {
this.datetime = new Date(datetime) ;
this.name = name;
this.unit = unit;
this.products = product ;
}
}
答案 0 :(得分:0)
使用没有构造函数和map
函数
export interface ProductTaken {
datetime: Date;
name: string;
unit: number;
products: Product[];
}
您的服务应具有map
功能
return this.http.get(...)
.map(res => <ProductTaken>res.json())
<强> LIVE DEMO 强>
答案 1 :(得分:0)
我找到了一个解决方案但是有人知道是否有更好的方法然后使用forEach。
class Product {
eating_time: Date;
qtytaken: number;
chart_bar = 1;
constructor(eating_time, qtytaken, chart_bar ) {
this.eating_time = new Date(eating_time);
this.qtytaken = dosage;
this.chart_bar = chart_bar;
}
}
export class ProductTaken {
datetime: Date;
name: string;
unit: number;
products: Product[];
constructor({datetime, name, unit, product} ) {
this.datetime = new Date(datetime) ;
this.name = name;
this.unit = unit;
let prodarray = [];
product.forEach(function(element) {
prodarray.push(new Product(element.eating_time, element.qtytaken, element.chart_bar));
this.products = prodarray ;
}
}