0

感谢您事先提供帮助。我正在尝试将 canDeactivate 函数与 NgbModal 一起使用。这意味着,我想返回的值取决于 NgbModal 的返回。

我已经看到它与 comfirm alert 一起使用,但它无法与 NgbModal 一起使用。这是我的代码,console.log(rtn) 打印“未定义”。我明白为什么,但不知道如何将 NgbModal 连接到 canDeactive()。请帮帮我!

  public canDeactivate() { 
    //return confirm("Do you really want to leave?")
    const rtn = this.ExistFromExamModal(this.exitFromExamMd)
    console.log(rtn)
    return rtn
  }

  public ExistFromExamModal(content: any): any {
    this.modalService
      .open(content, {
        centered: true,
        scrollable: true,
        windowClass: 'final-confirm',
      })
      .result.then((result) => {
        if (result === 'yes') {
          return true
        } else {
          return false
        }
      })
  }
4

1 回答 1

2

您将需要返回一个可观察的

  public canDeactivate() { 
    return from(
      this.modalService
        .open(this.exitFromExamMd, {
          centered: true,
          scrollable: true,
          windowClass: 'final-confirm',
        }).result
    ).pipe(
      map(result => result === 'yes')
    );
  }

from 将 promise 转换为 observable,map 函数将 yes|no 字符串转换为布尔值。

编辑:实际上你可以让你的 ExistFromExamModal 函数返回一个承诺。目前它什么都不返回,但如果你return之前this.modalService它会返回一个承诺。

于 2020-09-08T02:16:44.173 回答