【发布时间】:2021-11-03 07:13:51
【问题描述】:
所以我试图将对象推入一个数组。如果我 console.log() 对象被打印到控制台。所以它们不是未定义的。但是如果我尝试推送它们,它会显示:“错误:未捕获(承诺):TypeError:无法读取未定义的属性(读取'推送')”。
这是我的代码:
let snapProtections = JSON.parse(snapshot.protection);
this.completeMachine.operationModes = snapOperationModes;
snapProtections.forEach(async prot => {
this.test.push(await this.protectionDataAcessService.getProtectionAndOperationModesByProtectionId(prot.id));
});
test 是 ProtectionAndOperationModes 类型的数组:
export interface ProtectionAndOperationModes {
protection: Protection;
operationModes: OperationMode[];
image?: EntityImage;
}
这是 getProtectionAndOperationModesByProtectionId 函数:
public async getProtectionAndOperationModesByProtectionId(protectionId: string): Promise<ProtectionAndOperationModes> {
const protection = await this.protectionService.getById(protectionId);
return await this.getOperationModesOfProtection(protection);
}
private async getOperationModesOfProtection(protection: Protection): Promise<ProtectionAndOperationModes> {
const availableOperationModes = await this.operationModeService.getByMachineId(protection.machineId);
const linkedOperationModes = await this.protectionLinkService.getByProtectionId(protection.id);
const image = await this.imageService.getByEntityId(protection.id);
return {
protection: protection,
operationModes: availableOperationModes.filter(o => linkedOperationModes.find(l => l.operationModeId === o.id)),
image: image
};
}
对如何将对象放入数组有任何帮助吗?
【问题讨论】:
-
似乎
this.testbis 不是数组但未定义... -
这是一个常见的错误和常见的问题。您不能在同步 Array 方法(map、filter、forEach 等)中使用
await。它不起作用(不等待)。您必须改用for循环。
标签: javascript angular typescript