我创建了一个小型服务,以显示使用Angular的Ionic应用程序的一些警报弹出窗口,这是我使用此服务的方式:
this.alertService.confirmAlert(
{
headerText: 'PAGES.CONFIRM_DELETE.TEXT',
cancelButtonText: 'PAGES.CANCEL_BUTTON',
confirmButtonText: 'PAGES.CONFIRM_BUTTON',
confirmButtonHandler: this.deleteDevice
}
);
我的问题是,在deleteDevice
函数中,我使用了当前组件中的变量,当调用它时(当我按下确认按钮时),该变量是未定义的,因为它使用了this
服务。
我也尝试将函数直接放在此处,但没有任何变化,我也尝试在函数参数中添加this
,例如:confirmButtonHandler: this.deleteDevice(this)
,但是这样,当我将处理程序直接调用时创建弹出窗口,而不是单击按钮时创建弹出窗口。
该如何解决?
编辑: 这是alertConfirm代码:
async confirmAlert({headerText, subHeaderText = null, messageText = null, cancelButtonText = null, cancelButtonHandler = null, confirmButtonText = null, confirmButtonHandler = null, type = null}) {
let textToTranslate = [];
textToTranslate.push(headerText);
if (subHeaderText) textToTranslate.push(subHeaderText);
if (messageText) textToTranslate.push(messageText);
if (cancelButtonText) textToTranslate.push(cancelButtonText);
if (confirmButtonText) textToTranslate.push(confirmButtonText);
let buttons = [];
this.translate.get(textToTranslate).subscribe(async translation => {
if (cancelButtonText) {
buttons.push({
text: translation[cancelButtonText],
role: 'cancel',
cssClass: 'button-cancel',
handler: (blah) => {
if (cancelButtonHandler) {
cancelButtonHandler();
}
}
});
}
if (confirmButtonText) {
buttons.push({
text: translation[confirmButtonText],
cssClass: 'button-confirm',
handler: (blah) => {
if (confirmButtonHandler) {
confirmButtonHandler();
}
}
});
}
const alert = await this.alertController.create({
header: translation[headerText],
subHeader: translation[subHeaderText],
message: translation[messageText],
buttons: buttons,
cssClass: ['confirm-popup', type ? type + '-popup' : ''],
});
await alert.present();
});
}