To use the following function, you must first import AlertController from the library:
import { AlertController } from '@ionic/angular';
The next step is to inject it into the constructor of any component:
export class myPage implements OnInit {
...data
constructor(private alertCtrl: AlertController){}
...data
}
Next, we have the following method of the class that I have created:
async getAlert(
title, message, cancelText, okText, cancelCallback, okCallback, params
){
const defaultTranslatedOptions = {
cancelText: "Cancelar",
okText: "Rechazar"
};
const alert = await this.alertCtrl.create({
header: title,
message: message,
buttons: [
{
text: cancelText ? cancelText : defaultTranslatedOptions.cancelText,
role: 'cancel',
cssClass: 'secondary',
handler: function(){
cancelCallback(...params[0]);
}
}, {
text: okText ? okText : defaultTranslatedOptions.okText,
handler: function(){
okCallback(...params[1]);
}
}
]
});
return await alert.present();
}
What this method allows is to create an alert on the screen with two buttons in a dynamic way, (according to the data that is passed to the method), including data such as the title of the alert, the description of the alert, the names that will have the buttons, the functions that these will execute when one button or another is pressed, and the arguments that will be passed to each function.
The problem is that if I call this method within another method of the SAME class and pass it as arguments 5 and 6, methods of the same class, I get in any of the two methods executed by the getAlert() method that this is undefined :
requestSendingOptions(){
const roomData = {
room: scrambleStringByCharset(ALLOWED_ROOMID_CHARS, 7) + ";" + Date.now,
name: this.userData.username,
type_user: this.userData.type_user
};
this.getAlert(
'¿Qué deseas hacer?',
'¿Deseas crear un nuevo grupo o añadir los invitados a un grupo existente?',
'Crear nuevo grupo', 'Añadir a grupo existente',
this.createNewRoom,
this.toRoomSelection,
[
['new-room', roomData],
[]
]
);
}
Now... the callbacks that are executed by means of the getAlert method , which in turn is executed by the requestSendingOptions method of the same class , is really irrelevant since the method has something inside or not, when I put it a console.log() to see the content of this according to the option that I have chosen in the alert to each of the two methods used , in both it tells me that this is undefined .
I have found a very simple solution... and it is to use bind: