I have tried researching on the use of async and await but i dont understand. what is the use of it in layman terms? and where can we use it?
like in this example, what is async or the function is trying to do.
Example of async and await
resetPassword(email: string) {
this.angularFire.sendPasswordResetEmail(email).then(async () => {
let alert = await this.alertCtrl.create({
header: 'Reset Password',
message: 'Password reset email sent! Check your inbox.',
buttons: [{
text: "OK",
handler: () => {
this.navCtrl.pop();
}
}]
})
await alert.present();
}).catch(async () => {
let alert = await this.alertCtrl.create({
header: 'Alert',
message: "Email or account does not exist. Please try again with a valid email or account!",
buttons: [{
text: "OK",
handler: () => { }
}]
})
await alert.present();
});
}
Related
I am integrating PayPal in ionic3 app, whenever I click on make payment it redirects to paypal site, there I enter username and password and each time it says "invalid username and/or password", but I am adding correct credentials for login.
please help
Here the code:
import { PayPal, PayPalPayment, PayPalConfiguration } from '#ionic-native/paypal';
payWithPaypal(){
//let amount = parseFloat(HomePage.orderinfo.total);
this.payPal.init({
PayPalEnvironmentProduction: 'AdXXXXXXXXXXXXXXXX',
PayPalEnvironmentSandbox: 'YOUR KEY'
}).then(() => {
this.payPal.prepareToRender('PayPalEnvironmentProduction', new PayPalConfiguration({
})).then(() => {
let payment = new PayPalPayment(this.paymentAmount, this.currency, 'description', 'sale');
this.payPal.renderSinglePaymentUI(payment).then((res) => {
this.online('PAYPAL',res.response.id);
this.responseData = JSON.stringify(res, null, 1);
let alert = this.alertCtrl.create({
title: 'La orden ha sido agregada',
subTitle: "El id de su gestion es: " + res.order_number,
buttons: [{
text: "OK",
handler: () => {
this.navCtrl.setRoot(HomePage);
this.navCtrl.push(OrderConfirmPage,{ OrderId: this.responseData.success });
}
}]
});
alert.present();
}, (err) => {
let alert = this.alertCtrl.create({
title: 'Error intentando conectar',
subTitle: err,
buttons: ['Dismiss']
});
alert.present();
});
}, (err) => {
let alert = this.alertCtrl.create({
title: 'Error con la configuracion',
subTitle: err,
buttons: ['Dismiss']
});
alert.present();
});
}, (err) => {
let alert = this.alertCtrl.create({
title: 'Error con el plugin de PayPal',
subTitle: err,
buttons: ['Dismiss']
});
alert.present();
});
}
This is the screen capture
I'm trying to use Ionic FileTransfer, but it always returns me with this response:
PS: The url is a direct link to the download
I really have no idea of whats wrong in this code
FileTransferError
{
body:null,
code:null,
exception:null,
http_status:null,
source:null,
target:null
}
My code:
const storageDirectory = '';
this.platform.ready().then(() => {
storageDirectory = cordova.file.externalRootDirectory;
let url = this.apiURL + itemId
const fileTransfer: FileTransferObject = this.transfer.create();
fileTransfer.download(url, storageDirectory + "item" + itemId+ ".xml")
.then(response => {
const alertSuccess = this.alertCtrl.create({
title: `Successfully downloaded!`,
subTitle: `The file is in: \n: ${response.toURL()}`,
buttons: ['Ok']
});
alertSuccess.present();
})
.catch(err => {
const alert = this.alertCtrl.create({
title: 'Error!',
subTitle: 'Try again!',
buttons: [{
text: 'OK',
handler: () => {
this.util.getPermission();
}
}]
});
alert.present();
});
})
}
I am getting a push notification using Firebase and showing it in alert box. Now I want to display the message i received in a text field so that user can edit the message.I also want to output the message in console.
pushObject.on('notification').subscribe((notification: any) => {
if (notification.additionalData.foreground) {
let youralert = this.alertCtrl.create({
title: 'New Push notification',
message: notification.message,
buttons: [
{
text: 'Cancel',
role: 'cancel',
handler: () => {
console.log('Cancel clicked');
}
},
{
text: 'Okay',
handler: () => {
console.log('Okay clicked');
}
}
]
});
There's a inputs property on the Alert interfacce, it works pretty much like the buttons. It's an array of objects and you have a input value property to set the desired value.
Since i don't know where you want to log you value and if it's the value that has come from the server or the edited value, i'll show both.
pushObject.on('notification').subscribe((notification: any) => {
if (notification.additionalData.foreground) {
console.log('push message', notification.message);
let youralert = this.alertCtrl.create({
title: 'New Push notification',
inputs: [{
placeholder: 'Your placeholder..',
type: 'text',
name: 'yourInputName, // Name to get it in your handler callback
value: notification.message
}],
message: notification.message,
buttons: [
{
text: 'Cancel',
role: 'cancel',
handler: () => {
console.log('Cancel clicked');
}
},
{
text: 'Okay',
// you'll need to get the input data, so pass a parameter to the callback
handler: (data) => {
// here's the value user has edited in the input
console.log('Edited message', data.yourInputName);
console.log('Okay clicked');
}
}
]
});
Hope this helps
I have add one alert input field to change password,But How can we give validation to input field in ionic?
account.ts
changePassword(){
let alert = this.alertCtrl.create({
title: 'Change Password',
buttons: [
'Cancel']
});
alert.addInput({
name: 'Password',
value: this.password,
placeholder: 'password'
});
alert.addButton({
text: 'Ok',
handler: (data: any) => {
this.userData.setUsername(data.username);
let accountData=new FormData();
accountData.append('userid',this.userid),
accountData.append('password',data.Password)
this.works.changePassword(accountData).subscribe(res=>{
console.log(res),
err=>{
console.log(err)
}
})
}
});
alert.present();
}
You can use alert.setMessage('text') method to show validation message and don't forgot to add return false after validation to prevent alert dismiss.
public displayToAlert(title, subTitle) {
let alert = this.alertCtrl.create({
title: title,
subTitle: subTitle,
message: '',
enableBackdropDismiss: false,
inputs: [
{name: 'userEmail',
placeholder: 'Email Id'}
],
buttons: [{
text: 'Cancel',
handler: () => {
}
},{
text: 'Send',
handler: datas => {
if(datas.userEmail != null && datas.userEmail.length > 0){
this.onExportNew();
}else{
alert.setMessage('<b style="color: red;">Enter valid email id.</b>');
return false;
}
}
}]
});
alert.present();
}
For Reference : Alert controller input box validation
I have a class Action with it's method do() wherein the IonicAlert is called.
What I want to do now is, that I call something like
Action.do().then( () => { /* do domething */ } );
but only after OK was clicked on the alert.
do(): Promise<boolean> {
let alert = this.alertCtrl.create({
buttons: [{
text: 'OK',
handler: () => {
alert.dismiss().then( () => { /* do something */ });
return false;
}
}]
});
alert.present();
return null;
}
}
I added return null; only to get no error, but of course it's not working.
Any idea, how to solve this? Thanks
PS: I also posted it to the ionic forum: https://forum.ionicframework.com/t/ionic-alert-wait-until-button-is-pressed/67448
Found the solution with the help of this site: https://basarat.gitbooks.io/typescript/content/docs/promise.html
do(): Promise<boolean> {
return new Promise((resolve, reject) => {
let alert = this.alertCtrl.create({
buttons: [{
text: 'OK',
handler: () => {
alert.dismiss().then(() => { resolve(true); });
return false;
}
}]
});
alert.present();
});
}
}
Here a version who can return true or false :
showConfirm(): Promise<boolean> {
return new Promise((resolve, reject) =>{
const confirm = this.alertCtrl.create({
title : 'Are you sure ?',
buttons: [
{
text: 'Yes',
handler:_=> resolve(true)
},
{
text: 'No',
handler:_=> resolve(false)
}
]
}).present();
})
}
To call the promise :
this.showConfirm().then((result) => {
if(result){
// do something
}
})
This works for me
handler: () => {
console.log(this.viewCtrl.dismiss());
}
That code didn't work for me in Ionic4. This did:
presentAlert():Promise<boolean> {
return new Promise((resolve, reject) => {
const ctl = this.alertController;
let alert:any = this.alertController.create({
buttons: [{
text: 'OK',
handler: () => {
ctl.dismiss().then(() => { resolve(true); });
return false;
}
}]
}).then((dlg) => dlg.present());
});
}