ng-zorro modalService modalRef.afterClose.subscribe拿到结果是undefined

37 阅读1分钟

问题:

    "@angular/core": "^11.2.4",
    "ng-zorro-antd": "^11.2.0",
    this.modalRef = this.modalService.warning({
      nzTitle: '解绑提示',
      nzContent: '解绑后将不能使用该浏览器进行刷脸登录,您还要继续吗?',
      nzMaskClosable: false,
      nzClosable: false,
      nzOkText: '解绑',
      nzCancelText: '取消',
      nzOnOk: () => {      
        this.modalRef.close(true);
      }
    });
    this.modalRef.afterClose
      .subscribe((res: any) => {
      if (res) {
      console.log(res); // => undefined
      });

在modal的afterClose观察对象里拿到的值都是undefined,和github问题相似,无论this.modalRef.close()里传入什么,都拿不到。

解决思路:

这个问题是由于我们最近在升级angular项目,from 6 to 11.升级后检查功能时发现的,所以在angular6和ng-zorro@1.8.1里这样写是ok的,但是到新版本后,就不奏效了,于是我尝试各种解决方法:

  1. afterClose后面加上.pipe(take(1))去强制触发订阅对象complete,结果没用
  2. 在nzOnOk事件里直接订阅,打印,仍然是拿不到,说明了 this.modalRef.close里根本没有接收到传值。
  3. 最终,我想到用返回值的方法,return true;结果奏效,本来this.modalRef.close(true)和return true意义应该是相同的,但是在nz11里,直接传值方法不奏效了,目前未深究源码,如果有感兴趣的可以去看下。

感想:

这个问题不大,一行代码解决,但是我却花了将近60min的时间去搜索、研究,有几次觉得自己已经在正确的道路上了,结果发现还是歧途。所以,找对方法很重要,官方demo和文档一定要看,仔细看,(如果不想看源码的话).