async/await中then()内ViewChild为undefined的问题及原因咨询
补充说明
- 问题出在
async await上。 - 移除
async await,直接返回Promise后问题解决。 - 不知为何
async await内部的then()会丢失类对象的数据,求相关解释,谢谢大家:)
问题描述
在then()回调中使用ViewChild时,它的值为undefined。
代码示例
ViewChild定义
@ViewChild('listaLecturas') listaLecturas!: ITBlistaComponent
HTML代码
<div class="recepcion-lista-lecturas"> <itb-lista #listaLecturas [entidadActiva]="false" [parametros]="parametrosProductos" [configuracionColumnas]="configuracionProductos" [activarFiltro]="false"></itb-lista> </div>
方法代码
private async cargarLecturas(): Promise<void> { delete this.parametrosProductos['accion'] this.parametrosProductos['accion'] = 'LEER_RECEPCION_PROMOCION' console.log(this.listaLecturas) // 此处已定义 await this.datos.mantenimiento('LEER_RECEPCION_PROMOCION', this.parametrosProductos) .then( (registros) => this.montarLecturas(registros) ) .catch( (error) => console.log(error)) } private montarLecturas( registros: any ): void { this.listaLecturas.montarRegistros(registros) // 此处为undefined }
奇怪的是,在then()之前this.listaLecturas是已定义的状态。
调试情况
- 已定义状态截图
- undefined状态截图
我尝试过将组件作为参数传入方法:
private async cargarLecturas(): Promise<void> { delete this.parametrosProductos['accion'] this.parametrosProductos['accion'] = 'LEER_RECEPCION_PROMOCION' console.log(this.listaLecturas) await this.datos.mantenimiento('LEER_RECEPCION_PROMOCION', this.parametrosProductos) .then( (registros) => this.montarLecturas(registros, this.listaLecturas) ) .catch( (error) => console.log(error)) } private montarLecturas( registros: any, lista: ITBlistaComponent): void { lista.montarRegistros(registros) }
但lista依然是undefined。
内容的提问来源于stack exchange,提问作者dperez
相关产品推荐
相关产品推荐

