我有一个函数 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);
})
}
result
从订阅 this.modalRef.content.onClose
工作中。我可以成功登录 true
或 false
.当结果变为 true
或 false
不过,我如何返回 true
或 false
作为 canDeactivate
的值?还是我没捕获要点,我应该换一种方式做事吗?
我的 ConfirmationComponent
看起来像这样,它定义了 onClose
作为Observable<boolean>
(特别是 Subject<boolean>
),所以我可以成功返回一个 bool 值可观察值,但我如何获得我的 canDeactivate
返回 true
或 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();
}
}
最佳答案
感谢@David,我将对 onClose
的订阅更改为 map
而不是 subscribe
并且这有效:
openConfirmDialog() {
this.modalRef = this.modalService.show(ConfirmationComponent);
// line below - change from 'subscribe' to 'map'
return this.modalRef.content.onClose.map(result => {
return result;
})
}
但是,正如@Ingo Burk 所指出的,我可以简单地使用:
openConfirmDialog() {
this.modalRef = this.modalService.show(ConfirmationComponent);
return this.modalRef.content.onClose;
}
关于javascript - Angular observable - 如何从订阅返回 true 或 false 到 observable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50442339/