所以我从我的asp.net核心api获得以下
JSON结构:
{ "contentType": null,"serializerSettings": null,"statusCode": null,"value": { "productName": "Test","shortDescription": "Test 123","imageUri": "https://bla.com/bla","productCode": null,"continuationToken": null } }
public externalProduct: ProductVM; getProductExternal(code: string): Observable<ProductVM> { return this.http.get("api/product?productCode=" + code) .map((data: ProductVM) => { this.externalProduct = data; //not working... console.log("DATA: " + data); console.log("DATA: " + data['value']); return data; }); }
ProductVM:
export interface ProductVM { productName: string; shortDescription: string; imageUri: string; productCode: string; continuationToken: string; }
我的问题是我无法将其反序列化为ProductVM.控制台日志只生成[object Object]
我如何实际将json响应中的值的内容映射到ProductVM对象?
说数据是map函数中的ProductVM是错误的吗?我尝试了很多不同的组合,但我无法让它发挥作用!
我不确定我是否能以某种方式自动告诉angular将json响应中的值数组映射到ProductVM对象,或者我是否应该向ProductVM类提供构造函数(它现在是一个接口),并提取特定的值. json手动?
解决方法
链接到http的map方法中的数据对象被视为Object类型的对象.此类型没有您需要访问的值成员,因此类型检查器不满意.
键入的对象(不是任何对象)只能分配给无类型对象或完全相同类型的对象.此处,您的数据类型为Object,不能分配给ProductVM类型的另一个对象.
绕过类型检查的一种解决方案是将数据对象转换为任何无类型对象.这将允许访问任何方法或成员,就像普通的旧Javascript一样.
getProductExternal(code: string): Observable<ProductVM> { return this.http.get("api/product?productCode=" + code) .map((data: any) => this.externalProduct = data.value); }
另一种解决方案是更改您的API,以便数据可以使用data.json()传递其内容.这样,您就不必绕过类型检查,因为json()方法返回一个无类型值.
但要小心,因为如果您将来添加它们,您的任何对象都不会有ProductVM的方法.您需要手动创建一个带有新ProductVM()和Object.assign的实例才能访问这些方法.