我有以下代码:
private resetPassword() {
this.auth.subscribe(auth => {
this.firebaseRef.auth().sendPasswordResetEmail(auth.auth.email).then(
success => {
this.successMessage = 'A password reset email was sent to ' + auth.auth.email + '. Please follow' +
'the instructions in the email to reset your password.';
},
error => {
console.log(error);
}
)
});
}
我遇到的问题是 this.successMessage
未设置为成功。我可以放一个 console.log
在那里,它可以工作,但似乎我无法在该范围内引用 this
。我尝试过尽可能使用 .bind(this)
,但没有帮助。有什么想法吗?
请注意,这是一个 Angular2 应用程序,并且 successMessage
正在模板中呈现,因此我知道它不起作用。我已经确认,如果我将消息设置在 then
之外,它就能正常工作。
最佳答案
感谢@AR7,我找到了解决方案。 this.successMessage
已正确更新,但 Angular2 模板未更新。我通过将 this.successMessage
赋值包装在 ngZone.run
中解决了这个问题:
constructor(private ngZone: NgZone) {}
...
private resetPassword() {
this.auth.subscribe(auth => {
this.firebaseRef.auth().sendPasswordResetEmail(auth.auth.email).then(
success => {
this.ngZone.run(() => {
this.successMessage = 'A password reset email was sent to ' + auth.auth.email + '. Please follow' +
'the instructions in the email to reset your password.';
});
console.log(this);
},
error => {
console.log(error);
}
)
});
}
关于javascript - 在 promise 回调中使用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41924196/