我有这个警告:
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);
}
但我明白了:测试:未定义
您还可以尝试以下方法:
this.service.showConfirm('title', 'message', 'Cancel', 'OK, () => this.test('test param'), null);
我总觉得这是做这种事最优雅的方式。
你应该传递如下参数:
this.service.showConfirm('title', 'message', 'Cancel', 'OK', this.test.bind(this, 'Yes'), null);
注意参数this.test.bind(this, 'Yes')
。您应该将this
上下文(组件)传递给被调用函数,因为您的test
方法存在于组件上。
this.contractorService.showConfirm("Continue?", "Your credit card will be charged", "Cancel", "OK", this.test.bind(this.test, 'a'), this.cancel);
所以我想我们需要传递带参数的函数。以上是有效的。