Angular 2 - 在服务中创建警报

问题描述 投票:1回答:3

我有这个警告:

contractorService.ts:

public showConfirm(title: string, message: string, cancelBtnTxt: string, confirmBtnTxt: string, confirmFunc: any, cancelFunc: any): void {
    console.log("confirmFunc: ", confirmFunc);
    const confirm = this.alertCtrl.create({
      title: title,
      message: message,
      buttons: [
        {
          text: cancelBtnTxt,
          handler: () => {
            cancelFunc();
          }
        },
        {
          text: confirmBtnTxt,
          handler: () => {
            confirmFunc();
          }
        }
      ]
    });
    confirm.present();
  }

我有服务,我想我可能需要从其他地方打电话。如何通过参数传递确认和取消功能。

requestComponent.ts:

public test(): void {
    console.log('test');
}

requestComponent.ts:中的其他一些功能

someFunc(): void {
    this.service.showConfirm('title', 'message', 'Cancel', 'OK, this.test, null);
}

上面的工作,但后来我试过:

public test(param: any): void {
    console.log('test: ', param); // param is undefined.
}

someFunc(): void {
    this.service.showConfirm('title', 'message', 'Cancel', 'OK, this.test.bind('test param'), null);
}

但我明白了:测试:未定义

angular typescript
3个回答
1
投票

您还可以尝试以下方法:

this.service.showConfirm('title', 'message', 'Cancel', 'OK, () => this.test('test param'), null);

我总觉得这是做这种事最优雅的方式。


1
投票

你应该传递如下参数:

this.service.showConfirm('title', 'message', 'Cancel', 'OK', this.test.bind(this, 'Yes'), null);

注意参数this.test.bind(this, 'Yes')。您应该将this上下文(组件)传递给被调用函数,因为您的test方法存在于组件上。


0
投票
this.contractorService.showConfirm("Continue?", "Your credit card will be charged", "Cancel", "OK", this.test.bind(this.test, 'a'), this.cancel);

所以我想我们需要传递带参数的函数。以上是有效的。

© www.soinside.com 2019 - 2024. All rights reserved.