【发布时间】:2019-01-08 15:36:54
【问题描述】:
我正在尝试将我的 http.get 响应转换为实际对象 -> 在我的特定情况下是复杂对象数组。
在不需要任何特定转换的正常情况下,您可以执行以下操作(简化):
return this.httpClient.get(api, this._options_get)
.pipe(
map((response: any) => {
return response.value as NewProduct[];
})
);
由于我需要将其实际转换为对象,因此我创建了此静态方法:
static toProduct(otherProduct: any): NewProduct {
let item = new NewProduct();
Object.keys(otherProduct).forEach(prop => {
if (typeof otherProduct[prop] === "object" && otherProduct[prop]) {
if (!item.hasOwnProperty(prop))
item[prop] = otherProduct[prop];
Object.assign(item[prop], otherProduct[prop]);
}
else
item[prop] = otherProduct[prop];
})
return item;
}
在Object.assign 下,我正在获取已在第一行下初始化的现有对象,我只是将otherProduct 中的所有属性复制到它。但是,当涉及到对象数组时,我开始面临问题。示例(带有简化类):
export class Person {
name:string;
age:number;
addresses:Address[] = [];
}
export class Address {
street:string;
city:string;
fullAddress() : string { return this.street + this.city; }
}
一旦有了这种数组,item 中就没有任何初始对象。这意味着没有导致简单Object 的类的初始构造函数。这对 JavaScript 或 TypeScript 来说没有错误;然而,当我试图访问一个类的内部方法时(在我们的简化案例fullAddress() 中,我将无法访问。
我需要它的原因是我在子类上覆盖了toString() 方法,当您使用filter 方法(适用于字符串)时,这对于MatTableDataSource 是必需的。
有没有办法从http.get() 检索元素并将结果正确映射到类型化对象?
【问题讨论】:
标签: json angular typescript casting jsonserializer