1

我有一个canDeactivate应该返回true或返回的函数false。这可以通过调用openConfirmDialog()函数的结果来确定,该函数会打开 ngx-bootstrap 模态“确认”对话框并等待用户响应(可能导致truefalse)。这是代码:

  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正在工作。我可以成功登录truefalse. 当结果变为要么truefalse虽然,我如何返回 truefalse作为值canDeactivate?还是我错过了重点,我应该以不同的方式做事吗?

我的ConfirmationComponent看起来像这样,它定义onCloseObservable<boolean>(特别是 a Subject<boolean>),所以我可以成功返回一个布尔可观察对象,但是我如何让我canDeactivate的返回truefalse何时openConfirmDialog收到 or 的truefalse

@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();
    }
}
4

1 回答 1

1

感谢@David,我将订阅更改onClose为 amap而不是 a 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;
  }
于 2018-05-21T06:16:08.823 回答