【问题标题】:Why are variables not updating?为什么变量不更新?
【发布时间】:2018-08-01 13:29:42
【问题描述】:

我可能正在监督某些事情,但我被卡住了,以下变量在 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 承诺之外的其他地方更新变量时,它可以正常工作——我非常困惑......

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

我将非常感谢您的帮助:)

【问题讨论】:

  • 如果我没记错的话,将变量设置为private 这意味着它们无法在模板中访问。这表明它们对于 class 打字稿文件是私有的。

标签: angular typescript


【解决方案1】:

(假设.signInWithPopup是一个web-request,或者其他异步调用)

角度变化检测运行以响应使用与组件的交互。如果值在该事件处理之外更新,您需要手动告知组件它已更改。

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 vs private cmets:

这些类型描述符是 TypeScript 语言结构。一旦 TypeScript 被编译成 JavaScript,它们就不会影响应用程序的运行方式。 TypeScript 编译器只能检测来自其他 TypeScript 的访问错误 - 来自模板的访问(实际上)不受限制。

补充讨论:"private" and "public" in Angular 2 component

【讨论】:

  • 您好@Vlad274,非常感谢您的回答。这绝对引导我走向正确的方向。我什至不知道这种更改检测/模板渲染工具是否存在;)...非常有帮助。不太清楚为什么,但 .markForCheck() 对我不起作用,而是我使用 this.changeDetector.detectChanges()
【解决方案2】:

您好,您的变量的访问是私有的,如果您想直接从模板访问,您必须更改为公共,否则您需要使用模板中的函数或公共内容返回。

【讨论】:

  • 这是正确的......我不知道为什么它被否决了?
猜你喜欢
  • 2019-08-19
  • 1970-01-01
  • 1970-01-01
  • 2010-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-13
  • 1970-01-01
相关资源
最近更新 更多