Así que estoy tratando de empujar objetos a una matriz. Si hago console.log(), los objetos se imprimen en la consola. Así que no están indefinidos. Pero si trato de presionarlos, dice: "Error: no capturado (en promesa): TypeError: no se pueden leer las propiedades de undefined (leyendo 'push')".
Aquí está mi código:
let snapProtections = JSON.parse(snapshot.protection); this.completeMachine.operationModes = snapOperationModes; snapProtections.forEach(async prot => { this.test.push(await this.protectionDataAcessService.getProtectionAndOperationModesByProtectionId(prot.id)); });test es una matriz de tipo ProtectionAndOperationModes:
export interface ProtectionAndOperationModes { protection: Protection; operationModes: OperationMode[]; image?: EntityImage; }Esta es la función 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 }; }¿Alguna ayuda sobre cómo colocar los objetos en una matriz?
De acuerdo, simplemente salté a su código y no leí completamente que el error que está recibiendo está empujando a una matriz inexistente. Dejaré el original ya que este será un problema de seguimiento :)
Su variable this.test no está definida, por lo tanto, no puede presionarla. Puede solucionar el problema sin presionarlo sino asignando la variable directamente, o asegurándose de que exista de antemano. En mi respuesta original también mostré una forma de hacerlo (la última línea del código).
Tu código funciona, solo que no de la manera que esperas. El empuje ocurre de forma asincrónica, por lo que lo más probable es que lo observes demasiado pronto.
Para esperar hasta que se llene su matriz, debe esperar todas sus promesas de esta manera:
let snapProtections = JSON.parse(snapshot.protection); this.completeMachine.operationModes = snapOperationModes; // protectionModes will contain an array of the resolved promises values const protectionModes:ProtectionAndOperationModes[] = await Promise.all( // map the prots to an array of promises and await that array using promise.all snapProtections.map(prot => this.protectionDataAcessService.getProtectionAndOperationModesByProtectionId(prot.id)) ); protectionModes.forEach(mode => this.test.push(mode)); // or use spread: this.test.push(...protectionModes); // or just assign to it this.test = protectionModes;De esta manera, sus datos se completarán después de este código.