我有一个对话框组件,当对话框关闭时,用户的输入被注册。然后使用该输入来检查是否运行下一个函数。
但是,我意识到该变量永远不会立即更改为用户选择的内容,它保持未定义状态,直到下次对话框再次打开和关闭。
我读到Javascript默认情况下同步运行函数,所以我尝试将它们分成两个不同的函数,但也无济于事。
代码如下:
openDialog() {
const dialogRef = this.dialogService.open(ConfirmationDialogComponent, {
context: {
name: this.name,
details: this.details,
},
}).onClose.subscribe(confirm => this.confirm = confirm);
console.log(this.confirm); //returns undefined
if (this.confirm === true) { //doesn't run until dialog is opened and closed the second time
console.log('true');
this.record();
}
}
附:我的对话框使用 Angular ngx-admin 库。所以 .onClose() === .afterClosed() 对于正常的 Angular 对话框。
感谢帮助,谢谢!
最佳答案
将代码放入 subscribe() 方法中,例如:
openDialog() {
const dialogRef = this.dialogService.open(ConfirmationDialogComponent, {
context: {
name: this.name,
details: this.details,
},
}).onClose.subscribe(confirm => {
if(confirm) {
console.log(confirm);
this.record();
}
});
}
}
关于javascript - 确保下一个函数仅在对话框关闭后运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56801422/