You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决传入MatDialog模态框的listCategorie数据为空的问题

问题原因

  • 执行顺序错误:你当前的代码是先构造模态框配置、打开模态框,才发起分类数据请求,请求未完成时listCategorie还是初始空值,自然传递给模态框的数据为空
  • getcategorie方法没有返回Promise实例,async/await不会等待接口请求完成,相当于异步等待逻辑失效

修复方案

先修改getcategorie方法,返回Promise以支持正确的异步等待:

getcategorie(): Promise<void> {
  return this.LCategorieService.getCategories(this.id).then((res )=> {
    this.listCategorie = res;
  })
}

再调整addNoteModal的执行顺序,先等待数据请求完成,再初始化打开模态框:

async addNoteModal() {
  // 先请求分类数据
  try {
    await this.getcategorie();
  } catch (error) {
    console.error("获取分类数据失败", error);
    // 可在这里添加请求失败的提示逻辑
    return;
  }

  // 数据请求完成后再构造模态框配置、打开模态框
  const dialogConfig = new MatDialogConfig();
  dialogConfig.disableClose = false;
  dialogConfig.autoFocus = true;
  dialogConfig.data = {
    ismodal: true,
    idExamen: this.id,
    list: this.listCategorie
  };  
  console.log('传递给模态框的分类数据', this.listCategorie);

  this.dialog.open(NoteModalComponent, dialogConfig);
}

可选扩展方案

如果你的场景需要先弹出模态框、再加载数据避免用户等待,可以在拿到数据后主动更新模态框实例的参数:

async addNoteModal() {
  const dialogConfig = new MatDialogConfig();
  dialogConfig.disableClose = false;
  dialogConfig.autoFocus = true;
  dialogConfig.data = {
    ismodal: true,
    idExamen: this.id,
    list: []
  };  
  // 先打开模态框拿到实例
  const dialogRef = this.dialog.open(NoteModalComponent, dialogConfig);

  try {
    await this.getcategorie();
    // 请求完成后更新模态框的入参
    dialogRef.componentInstance.data.list = this.listCategorie;
  } catch (error) {
    console.error("获取分类数据失败", error);
  }
}

内容的提问来源于stack exchange,提问作者drnwork

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 08:54:02