[ng-bootstrap]:将功能传递给模式引发了服务

时间:2018-11-07 13:26:06

标签: javascript angular ng-bootstrap

我已经创建了一个服务,该服务调用了我的不同模式。因此,我有一个模态调用“ Confirm Modal”,它可以包含3个参数,confirm函数,拒绝函数和主体。这是以下模式:

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永不调用,因此如何通过服务将组件中的函数传递给我的模态?

2 个答案:

答案 0 :(得分:1)

在您的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;

答案 1 :(得分:0)

如果要在与modal相关的组件中调用方法,只需像这样调用它 this.modalRef.content.yourfunction();