gpt4 book ai didi

JSON 数据无法映射到我导出的接口(interface)?

转载 作者:搜寻专家 更新时间:2023-10-30 21:23:35 25 4
gpt4 key购买 nike

我无法将我的 Angular HTML 绑定(bind)到我的 devices数组,因为我期望的对象看起来像不匹配。我想绑定(bind)到 device.modelName但它失败了,因为我实际取回的对象具有属性 ModelName没有驼峰!

谷歌搜索一个解决方案,我看到我应该使用类型断言,所以我通过添加 <DeviceStatus[]> 来做到这一点。导致行 <DeviceStatus[]>response.json());在我的组件类中。不幸的是,这似乎没有任何改变。

为什么我的 json 对象似乎没有被正确映射?

我的模型界面:

export interface DeviceStatus {
deviceId: string;
modelName: string;
}

我的组件:

export class FetchDataComponent {
public devices: Observable<DeviceStatus[]>;

constructor(http: Http) {
this.devices =
http.get('api/Devices')
.map((response: Response) => <DeviceStatus[]>response.json());

this.devices.subscribe(x => console.log(x));
}
}

Chrome 控制台中的结果:

(2) [Object, Object]
0: Object
DeviceId: "1"
ModelName: "Model Name"
...

最佳答案

Type assertion只通知编译器,它对实际数据没有任何作用,正如文档中所说:

A type assertion is like a type cast in other languages, but performs no special checking or restructuring of data

永远记住,typescript 中的类型系统不会被翻译成 javascript,所以在运行时你没有那个。

您需要自己进行转换:

this.devices =
http.get('api/Devices')
.map((response: Response) => response.json().map(device => ({
deviceId: device.DeviceId,
modelName: device.ModelName
}));

关于JSON 数据无法映射到我导出的接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44808060/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com