我目前正在使用 Typescript 使用 Angular、MySQL、Express 和 Node-JS 开发一个项目。我有一个 Angular 组件,它的作用是加载包含学生数据的 PrimeNG 表,这些数据来 self 的 Node.Js 应用服务器的 API。
该表还有一个删除和一个编辑选项,编辑选项会弹出一个对话框,其中某个学生的数据是从表中的相同数据加载的,也在同一个对话框上,两个下拉列表填充了来自执行 onInit() 的 API 调用的数据。
我的问题是,我通过对服务器进行 API 调用来实现动态填充 onInit 的下拉菜单,但是当调用一个函数时,它会挂起整个应用程序,甚至我的计算机也几乎挂起。我不知道如何优化它,或者我是否以错误的方式进行操作。
这是我的一些组件代码
ngOnInit() {
this.estudiantesService.getEstudiantes().subscribe(
res => {
this.estudiantes = res; //Data of the students for the table
},
err => console.error(err)
);
this.cargaDropdownSeccion(); //Loads data for dropdown, doesn't hang the app but is probably because at the time it only brings a single record
this.cargaDropdownEspecialidades(); //Loads data for dropdown, this hangs the whole thing by itself, it usually brings seven records from the db
}
cargaDropdownSeccion() {
this.seccionDrpdwn = [];
this.seccionDrpdwn.push({ label: 'Secciones', value: null });
this.seccionesService.getSecciones().subscribe(
res => {
this.secciones = res;
for (let i = 0; i < this.secciones.length; i++) {
this.seccionDrpdwn.push({ label: this.secciones[i].seccion, value: this.secciones[i].idSeccion });
}
},
err => console.error(err)
);
}
cargaDropdownEspecialidades() {
this.especialidadDrpdwn = [];
this.especialidadDrpdwn.push({ label: 'Especialidad', value: null });
console.log('aqui');
this.especialidadesService.getEspecialidades().subscribe(
res => {
this.especialidades = res;
console.log('sigo aqui');
for (let i = 0; i < this.especialidades.length; i++) {
this.especialidades.push({ label: this.especialidades[i].especialidad, value: this.especialidades[i].idEspecialidad });
}
},
err => console.error(err)
);
}
最佳答案
每次推送到 this.especialidades
时,都会增加 this.especialidades.length
这本质上使循环无限。
试试这个:
this.especialidadesService.getEspecialidades().subscribe(
res => {
this.especialidades = [];
for (let i = 0; i < res.length; i++) {
this.especialidades.push({ label: res[i].especialidad, value: res[i].idEspecialidad });
}
},
err => console.error(err)
);
关于javascript - Angular 页面挂起可能是由于内存使用率过高,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57118746/