如何设置对象 属性 不在同一个地方?

How to set objects property not at the same place?

我有一些模型,假设:

export interface Car {
  driverId: string;
  driverName: string;
  color: string;
}

在我的函数中,我想 return 来自这个模型的一个对象数组,但我只能在这个函数中发生几次异步调用后构建它,所以我想声明一个空数组这个模型并分配我拥有的相关属性:

  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 创建 Cars,您可以将其余属性标记为可选:

export interface Car {
  driverId: string;
  driverName?: string;
  color?: string;
}