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

Angular 13中如何等待Bootstrap模态框的响应?

解决Angular中Bootstrap模态框等待用户响应并获取返回值的问题

你的核心问题是showConfirmation()仅同步显示模态框,未返回异步结果,导致await无法等待用户点击按钮的操作。可以通过Promise包装用户交互实现需求,具体修改如下:

1. 修改Bootstrap模态框组件(bootstrap.component.ts)

添加Promise的resolve回调引用,将模态框显示方法改为返回Promise,在按钮点击时resolve对应值:

private resolveFn: (value: boolean) => void;

showConfirmation(): Promise<boolean> {
  this.confirmationModal.show();
  // 返回Promise并保存resolve函数
  return new Promise((resolve) => {
    this.resolveFn = resolve;
  });
}

closeConfirmation() {
  this.confirmationModal.hide();
  // 处理模态框直接关闭的情况(如点击背景),默认返回false
  if (this.resolveFn) {
    this.resolveFn(false);
    this.resolveFn = null;
  }
}

confirmationOk(): void {
  this.confirmationModal.hide();
  if (this.resolveFn) {
    this.resolveFn(true); // 确认时返回true
    this.resolveFn = null;
  }
}

confirmationDeclined(): void {
  this.confirmationModal.hide();
  if (this.resolveFn) {
    this.resolveFn(false); // 取消时返回false
    this.resolveFn = null;
  }
}

2. 父组件中调用(parent.component.ts)

确保调用方法为async函数,才能使用await等待Promise结果:

async handleConfirmation() {
  let x = await this.popupModal.showConfirmation();
  console.log(x); // 正确输出true(点击Yes)或false(点击No/关闭模态框)
}

原理说明

用户点击按钮属于异步操作,无法通过同步函数直接返回结果。用Promise包装后,showConfirmation()返回一个未完成的Promise,直到用户点击按钮时,调用保存的resolveFn完成Promise,父组件的await即可拿到对应返回值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 11:40:52