在promise中使用这个回调

时间:2017-01-29 18:06:03

标签: 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之外设置消息它可以正常工作。

1 个答案:

答案 0 :(得分:1)

感谢@ 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);
            }
        )
    });

}