[英]Promise chain returned by ngbModal.open is skipped
我正在组件中实现数据编辑。 首先,我必须检查其中一个数据字段是否已更改,如果是,则应打开一个确认弹出窗口。 如果用户确认更改,数据将被更新。
从updateData()
方法中,我调用isChangeConfirmed()
方法,该方法打开弹出窗口并检查是否在弹出窗口上单击了“保存”按钮。 如果是,则返回true
。 我希望在调用弹出窗口并检查结果后将控件返回给updateData()
方法。 现实中是先保存数据,然后弹出window。 我做错了什么?
组件.html
<button id="saveButton" type="button" (click)="updateData()" translate>BUTTON.SAVE</button>
<!-- POPUP -->
<ng-template #editModal let-modal>
<button type="submit" id="modalConfirmButton" (click)="modal.close('save')" class="btn btn-primary" translate>BUTTON.CONFIRM</button>
<button type="reset" id="modalCancelButton" (click)="modal.close('cancel')" class="btn btn-primary" translate>BUTTON.CANCEL</button>
</ng-template>
组件.ts
updateData() {
if (this.isChangeConfirmed()) {
// Some code which updates data
}
}
isChangeConfirmed(): boolean {
if (this.oldValue != this.newValue) {
this
.ngbModal
.open(this.editModal, { ariaLabelledBy: 'editModal' })
.result
.then((result) => {
return result == "save";
}, (reason) => {
return false;
});
}
return true;
}
问题是当您打开模式时, (result) => { /*asynchronous part*/ }
和(reason) => { /*asynchronous part*/ }
中的部分异步运行。 与上下文之外的部分相比,无法确定这些部分何时运行。 你的return false;
语句在异步上下文中,但您return true;
在它之外。 所以即使return false;
一块运行,你不知道它什么时候会发生,因为你不知道this.ngbModal.open()
什么时候会产生result
或reason
。 在您的情况下,似乎速度不够快,并且return true;
是比较快的。 但关键是不可能知道。
这一切都很好,但你不能把return true;
inside (result) => {... return true;}
要么,因为我想编译器会抱怨没有 return 语句。
我能想到的解决方法有两种:
// Some code which updates data
(result) => {... /* Some code which updates data*/ }
boolean
,而是返回一个Observable
,并在updateData()
中订阅该Observable
。 查找如何将 pipe 两个答案(result)
和(reason)
合并为一个Observable
,如何加入它们,从中创建一个Observable
并返回它。如果您使用第二个选项 go,我建议您查看 RxJS 运算符( https://rxjs.dev/guide/operators )。 此外,阅读有关反应式编程的文章也很有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.