我使用的是API,它确实会返回有关我的智能设备的信息。我想解析这个API提供的灯光列表。为此,我在我的角度应用程序中创建了一个model
,它应该类似于响应:
export class LightsModel {
public lightModel: LightModel
}
export class LightModel {
public state: StateModel;
}
export class StateModel {
public on: boolean;
}
也许这是构建模型的一种过度消耗的方法,但实际上响应非常大,所以我喜欢将模型拆分到多个类中,以便以后更容易地对单个实例进行操作。
答复如下:
{
"1": {
state: { on: true }
},
"2": {...},
"3": {...}
}
我的问题是,我的模型不符合响应,因为我得到一个可变数目的灯回来,所以我不能使用硬编码的结构。是否有一种基于响应的动态缩放模型的方法?
发布于 2020-05-17 15:04:03
有几种方法你可以这么做。
选项1:使用for...in
for (const lightId in myApiResponse) {
const yourLight: LightModel = myApiResponse[lightId];
//do something here
}
这是文档https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in
选项2:使用Object.keys()
const keys = Object.keys(myApiResponse); // this will give you array of light ids ["1","2", etc.]
const lights = keys.map(t=> myApiResponse[t] as LightModel);
以下是文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
至于定义类,请将LightsModel更改为:
interface MyInterface {
[lightId: string]: LightModel;
}
希望这能帮上忙,艾萨克
发布于 2020-05-17 15:01:04
我可能需要更多的细节,但似乎您只需要设置LightsModel
来支持LightModel
的数组。
类似于:
export class LightsModel {
public lightModels: LightModel[]
}
https://stackoverflow.com/questions/61853554
复制相似问题