Как использовать это в «глубокой» функции? - PullRequest
0 голосов
/ 21 июня 2019

Я создал небольшой сервис для отображения всплывающих окон с предупреждениями для моего приложения Ionic, использующего Angular, вот как я использую этот сервис:

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();

});

}

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...