I have been trying to check the user password on sweetAlert. But the subscribe
method keeps executing last and doesn't work well. Is there any possible way I can make this work?
here is my code.
swal.fire({
title: 'Confirm Password',
input: 'password',
confirmButtonText: 'Submit',
focusConfirm: false,
showLoaderOnConfirm: true,
preConfirm: (password) => {
if (password=='') {
swal.showValidationMessage(`Please enter login and password`)
}
else {
const userName = 'jhonDoe'
let a = this.checkPass(userName, password) // excuted 1st
console.log(a) // excuted 3rd ---- which should display if the user password success or not
}
}
})
checkPass(userName,password) {
this.userService.checkPassword(userName, password).subscribe((data: any) => { //excuted 2nd
setTimeout(() => { //excuted 4th
if (data.succeeded) {
return data.succeeded
} else {
console.log(data.errors[0].description)
return data.errors[0].code
}
}, 500)
},
(err: HttpErrorResponse) => {
return err
});
}
your userService.checkPassword
is an asynchronous method which returns an observable. The checkPass function dosnt return anything, since the returns are all in some abetrary sub functions.
function foo(){
setIntervall(() => {return 0;}, 0)
}
will not return anything.
You need to use an async strategy. The easiest way would be to return a Promise:
function checkPass(userName: string, password: string): Promise<boolean> {
return new Promise<boolean>((resolve, reject) => {
this.userService.checkPassword(userName, password).subscribe((data: any) => {
if (data.succeeded) {
resolve(data.succeeded);
} else {
console.log(data.errors[0].description)
reject(data.errors[0])
}
},
(err: HttpErrorResponse) => {
reject(err)
});
});
}
Afterwards you only need to await the result of the checkPass function, which isn't a problem since the method supports async results:
preConfirm: async (password) => {
if (password == '') {
swal.showValidationMessage(`Please enter login and password`)
} else {
const userName = 'jhonDoe'
let a = await this.checkPass(userName, password) // excuted 1st
console.log(a) // excuted 3rd ---- which should display if the user password success or not
}
}