[ng-bootstrap]:将函数传递给模态抛出服务

[ng-bootstrap]: Passing function to a modal threw a service

我已经创建了一个调用我的不同模式的服务。所以我有一个模态调用 "Confirm Modal",它可以接受 3 个参数,一个确认函数,一个拒绝函数和一个正文。以下是模态:

export class ConfirmModalComponent implements OnInit {
  @Output() acceptFunc;
  @Output() refuseFunc?;
  @Input() body: string;
  constructor(public activeModal: NgbActiveModal) {}

  ngOnInit() {}

  async confirmModal() {
    await this.acceptFunc;
    this.closeModal();
  }

  async refuseModal() {
    if (this.refuseFunc) await this.refuseFunc();
    this.closeModal();
  }

  closeModal() {
    this.activeModal.close('Modal Closed');
  }
}

在我的模态服务中,我创建了以下函数来打开这个模态

openConfirmModal(accept: <P = any>(props?: P) => void, body: string,         refuse?: <P = any>(props?: P) => void): NgbModalRef {
  const modalRef = this.modalService.open(ConfirmModalComponent, { size: 'lg' });
  modalRef.componentInstance.accept = accept;
  if (refuse) modalRef.componentInstance.refuse = refuse;
  modalRef.componentInstance.body = body;
  return modalRef;
}

`

我调用这个函数如下:

openConfirmModal() {
  this.modalService.openConfirmModal(this.myFunc.bind(this), 'Test')
}

myFunc() {
  console.log('Work !');
}

问题是我的函数 myFunc 从未被调用过,那么如何通过服务将函数从组件传递到我的模式?

在您的 ConfirmModalComponent 上,您没有调用带括号的方法,更改

async confirmModal() {
  await this.acceptFunc;
  this.closeModal();
}

async confirmModal() {
  await this.acceptFunc();
  this.closeModal();
}

并且在您的 openConfirmModal 方法中,您定义的函数名称与您在组件上使用的名称不同,请更改这两行

modalRef.componentInstance.accept = accept;
if (refuse) modalRef.componentInstance.refuse = refuse;

modalRef.componentInstance.acceptFunc = accept;
if (refuse) modalRef.componentInstance.refuseFunc = refuse;

如果想在组件中调用与modal相关的方法,就这样调用 this.modalRef.content.yourfunction();