我正在创建一个新线程,因为我在这里没有找到解决方案。
在离子型的javascript中,我遇到了一个问题,在这个问题中,我应该调用已经在firebase中定义的函数。以下是我的情况:
change(val){
firebase
.auth()
.signInWithEmailAndPassword(this.email,val.old_password)
.then(function(user) {
firebase
.auth()
.currentUser.updatePassword(val.new_password)
.then(function() {
console.log("pass changed");
### here the function to show the message
})
.catch(function(err) {
console.log("an error happend changing pass");
### here the function to show the message
});
})
.catch(function(err) {
console.log("a very bad error happend");
});
}
passwordChanged(){
this.alertCtrl.presentTimeAlert(
"Password changed",
"The process was successful",
"",
2
);
}
passError(){
this.alertCtrl.presentAlert(
"Error",
"An error occurred. \n Retry",
"Okay"
);
}我的目标是在更改pass或没有更改pass时显示一条消息。考虑到这个函数是异步的,我想使用passwordChanged和passError作为“回调”,但它们在firebase函数范围内没有定义。实际上,我的所有变量和函数都是未定义的,我应该在哪里显示消息。
知道我使用的是防火墙库并且它可能是正常的这种行为,有一些方法可以避免这个问题吗?
谢谢你的进阶。
发布于 2019-10-27 15:55:38
您可以尝试这种方法:
passwordChanged() {
this.alertCtrl.presentTimeAlert(
'Password changed',
'The process was successful',
'',
2
);
}
passError(changeErrors) {
this.alertCtrl.presentAlert(
'Error',
'An error occurred. \n Retry',
'Okay'
);
}
async change(val) {
const changeErrors = [];
///
// Try to login
const tryToLogIn = await firebase.auth().signInWithEmailAndPassword(this.email, val.old_password)
.catch((err) => {
console.error('A very bad error happend', err);
changeErrors.push(err);
return null;
});
if (tryToLogIn) {
///
// Try to update the password
const updatePassword = await new Promise((res) => {
firebase.auth().currentUser.updatePassword(val.new_password)
.then(() => { console.log('Password changed'); res(true); })
.catch((err) => { console.error('An error happend changing pass', err); changeErrors.push(err); res(false); });
});
if (updatePassword) {
// Password was updated
passwordChanged();
} else {
// Password was not updated
passError(changeErrors);
}
}
}发布于 2019-10-27 12:52:26
我认为您可以通过发布带有事件发射器的消息来达到您的目标,所以您可以使用外部的结果。
这里是一个例子
import { Events } from 'ionic-angular';
// first page (publish an event when a user is created)
constructor(public events: Events) {}
createUser(user) {
console.log('User created!')
this.events.publish('user:created', user, Date.now());
}
// second page (listen for the user created event after.
function is called)
constructor(public events: Events) {
events.subscribe('user:created', (user, time) => {
// user and time are the same arguments passed in.
`events.publish(user, time)`
console.log('Welcome', user, 'at', time);
});
}https://stackoverflow.com/questions/58578923
复制相似问题