为什么变量不更新

为什么变量不更新

本文介绍了为什么变量不更新?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可能正在监督某些事情,但是我被困住了,当在promise中更新以下变量时,以下变量似乎在模板中没有更新:

I am probably overseeing something, but I am stuck, the following variables do not seem to be updating in the template when their values are updated in the promise:

private emailDetected: boolean = false;
private detectedEmail: string = "";

detectEmailViaPassword() {
    this.afAuth.auth.signInWithPopup(new auth.GoogleAuthProvider()).then(authResult => {
        this.detectedEmail = authResult.user.email;
        this.emailDetected = true;
    }).catch(error => {
        console.log(error);
    });
}

记录变量时,它们似乎已更新,但是模板中什么也没有发生.当我从firebase auth promise以外的其他地方更新变量时,它可以正常工作-我非常困惑...

When logging the variables, it seems that they are updated, but nothing is happening in the template. When I update the variables from somewhere else than the firebase auth promise, it works correctly -- I am extremely confused...

在模板中正确引用了变量:{{detectedEmail}}

The variables are referred to correctly in the template: {{ detectedEmail }}

非常感谢您的帮助:)

推荐答案

(假设 .signInWithPopup 是网络请求或其他异步调用)

(Assuming .signInWithPopup is a web-request, or other asynchronous call)

响应于与组件的使用交互而运行角度变化检测.如果在事件处理之外更新了值,则需要手动告诉组件它已更改.

Angular change detection runs in response to use interaction with the component. If values are updated outside of that event handling, you need to manually tell the component that it has changed.

constructor(private changeDetector: ChangeDetectorRef){}

detectEmailViaPassword() {
    this.afAuth.auth.signInWithPopup(new auth.GoogleAuthProvider()).then(authResult => {
        this.detectedEmail = authResult.user.email;
        this.emailDetected = true;
        this.changeDetector.markForCheck();
    }).catch(error => {
        console.log(error);
    });
}

更多深度阅读:https://blog.thoughtram.io/angular/2016/02/22/angular-2-change-detection-explained.html

解决 public private 注释:

这些类型描述符是TypeScript语言构造.将TypeScript编译为JavaScript后,它们与应用程序的功能无关.TypeScript编译器只能检测来自其他TypeScript的访问错误-从模板的访问(实际上)是不受限制的.

These type descriptors are TypeScript language constructs. Once the TypeScript is compiled into JavaScript, they have no bearing on how the application functions. The TypeScript compiler can only detect access errors from other TypeScript - access from the template is (effectively) unrestricted.

其他讨论:私有""和公共"在Angular 2组件中

这篇关于为什么变量不更新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 23:19