Angular 9、如何将return值从NgbModal return值转为canDeactivate

Angular 9, How to return the value to canDeactivate from NgbModal return value

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

我已经看到它与 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
        }
      })
  }

您将需要 return 一个 observable

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

from 将 promise 转换为可观察对象,map 函数将 yes|no 字符串转换为布尔值。

编辑: 实际上你可以让你的 ExistFromExamModal 函数 return 成为一个承诺。目前它 return 什么都没有,但是如果你在 this.modalService 之前 return 它会 return 一个承诺。