我在 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;
}
}
不应该像下面这样吗?
我们使用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;
}
...