javascript - 在 promise 回调中使用它

标签 javascript promise angularfire2

我有以下代码:

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/

相关文章:

Angularfire2 显示 "Missing permissions"错误,而直接运行 firebase 没有问题

javascript - AngularJS : ng-change not working when i input. val() 与 jquery

javascript - 在 JavaScript 中取消转义 HTML 实体?

javascript - 为什么我的脚本没有在 div 中动态显示输入字符

javascript - Promise.all 的奇怪行为

javascript - Rxjs:map 方法不在 combineLatest 上执行

javascript - Cloud Firestore 每次读取定价

javascript - Google Places API - 使用城市查找地址

javascript - 从循环内的 Promise 值设置状态

javascript - Promise.all 和 for-await-of 的性能