簡體   English   中英

在承諾回調中使用這個

[英]Using this in promise callback

我有以下代碼:

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賦值包裝在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);
            }
        )
    });

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM