我有一些模型,可以说:
export interface Car {
driverId: string;
driverName: string;
color: string;
}
在我的函数中,我想从这个模型返回一个对象数组,但是我只能在这个函数中发生几次异步调用之后构建它,所以我想声明这个模型的一个空数组并分配我拥有的相关属性:
public getListOfCarObjects(): Car[] {
let listOfCars: Car[] = [];
self._serviceOne.getIds().subscribe(
(res: DriversInfo) => {
res.ids.map((id: string, idIndex: number) => {
listOfCars[idIndex].driverId = id;
// more stuff api calls below and building the object
...
}
但我收到此错误:
ERROR TypeError: Cannot set property 'driverId' of undefined
怎么样,我应该这样做吗?
谢谢!!
最佳答案
您必须在您引用的索引处创建对象实例。您可以在收到数据时创建它,方法是推送值或按索引设置:
listOfCars.push({ driverId: id, dirverName: "", color: "" });
listOfCars[idIndex] = { driverId: id, dirverName: "", color: "" };
由于您的界面指定需要所有属性,因此您必须在创建新对象时指定所有属性,就像我上面所做的那样。如果您想仅使用 anid 创建汽车
,您可以将其余属性标记为可选:
export interface Car {
driverId: string;
driverName?: string;
color?: string;
}
关于javascript - 如何将对象属性设置在不同的地方?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46164098/