【发布时间】:2018-05-22 07:24:52
【问题描述】:
我有一个函数 canDeactivate 应该返回 true 或 false。这可以通过调用openConfirmDialog() 函数的结果来确定,该函数会打开一个 ngx-bootstrap 模态“确认”对话框并等待用户响应(这可能导致true 或false)。代码如下:
canDeactivate(component: ComponentCanDeactivate): boolean | Observable<boolean> {
// if there are no pending changes, just allow deactivation; else confirm first
return component.canDeactivate() ?
true :
this.openConfirmDialog();
}
openConfirmDialog() {
this.modalRef = this.modalService.show(ConfirmationComponent);
return this.modalRef.content.onClose.subscribe(result => {
console.log('results', result);
})
}
订阅this.modalRef.content.onClose 的result 正在工作。我可以成功登录true 或false。但是,当结果变为true 或false 时,我如何返回 true 或false 作为canDeactivate 的值?还是我没有抓住重点,我应该以不同的方式做事吗?
我的ConfirmationComponent 看起来像这样,它将onClose 定义为Observable<boolean>(特别是Subject<boolean>),所以我可以成功返回一个可观察的布尔值,但是如何让我的canDeactivate 返回@ 987654342@ 或 false 每当 openConfirmDialog 收到 true 或 false 的值?
@Component({
templateUrl: './confirmation.component.html'
})
export class ConfirmationComponent {
public onClose: Subject<boolean>;
constructor(private _bsModalRef: BsModalRef) {
}
public ngOnInit(): void {
this.onClose = new Subject();
}
public onConfirm(): void {
this.onClose.next(true);
this._bsModalRef.hide();
}
public onCancel(): void {
this.onClose.next(false);
this._bsModalRef.hide();
}
}
【问题讨论】:
-
您可以将
onClose返回的可观察对象映射到布尔可观察对象。 canDeactivate 的接口期望返回 boolean、observable或 promise 类型 -
谢谢大卫,我想我已经按照你的建议去做了——我已经发布了更多代码来更深入地展示正在发生的事情。希望我现在已经澄清了我在问什么?
标签: javascript angular observable ngx-bootstrap-modal