在 Angular 函数中等待用户输入

问题描述 投票:0回答:1

我在 Angular 中有一个函数,我需要等待用户的响应,但我没有取得任何成功。我认为我应该使用“subscribe()”,但不完全理解如何以及何时使用它。我的通话目前如下所示:

theAnswer:boolean = wait showConfirmDialog("确认更改!", "您确定要取消更改吗?);

    async showConfirmDialog(title: string, message: string) {

var answer: boolean = false;

  this.dialog
  .confirmDialog({
    title: title,
    message: message,
    confirmCaption: 'Yes',
    cancelCaption: 'No'
  })
  .subscribe((yes) => {
    if (yes) {
      answer = true;
    }
    else {
      answer = false;
    };
  });

  console.log('selected answer ' + answer)
  return answer;
}

}

angular typescript async-await subscribe
1个回答
0
投票

不应该像下面这样吗?

我们使用await来解析promise,如果它是一个我假设的可观察量,我使用

lastValueFrom
将其转换为promise,以便
await
将起作用,如果
confirmDialog
返回一个promise,那么就没有需要
lastValueFrom

import { lastValueFrom } from 'rxjs';
....
async showConfirmDialog(title: string, message: string) {
  const answer = await lastValueFrom(this.dialog
    .confirmDialog({
      title: title,
      message: message,
      confirmCaption: 'Yes',
      cancelCaption: 'No'
    }))
  console.log('selected answer ' + answer)
  return answer;
}
...
© www.soinside.com 2019 - 2024. All rights reserved.