gpt4 book ai didi

javascript - *ngIf 上使用的 Angular 4 构造函数值

转载 作者:行者123 更新时间:2023-12-03 03:48:40 30 4
gpt4 key购买 nike

在下面的 typescript 代码中,我有一个值 moreinfo我将其初始化为 1。之后,在构造函数内,我将值更改为 2。因此,对于值 1,我显示一个 div*ngIf对于值 2,我显示不同的 div 。一切都很完美,我看到该值已从控制台正确更改为 2。

export class LoginComponent implements OnInit {
moreinfo: number=1;
email: string;
password: string;

constructor(public afAuth: AngularFireAuth, public af:
AngularFireDatabase,public authService: AuthService) {

firebase.auth().onAuthStateChanged(function(user) {
if (user) {
this.moreinfo=2;
var user2 = firebase.auth().currentUser;
console.log("Current user id:" + user2.uid + "\nMoreinfo:" + this.moreinfo);
} else {
console.log("No user is signed in.");
}
});
}
}

但是,当我比较 HTML 中的值时,它显示 divmorevalue == 1;尽管该值已更改为 2。有没有人可以阐明我的问题?

<div class="container" *ngIf="moreinfo == 1">
<h1 *ngIf="authService.user | async">Welcome {{ (authService.user | async)?.email }}!</h1>
</div>

<div class="container" *ngIf="moreinfo == 2">
something
</div>

最佳答案

我认为这是因为您使用的闭包不正确,而不是匿名函数,请尝试使用箭头函数,它应该在组件中设置值 - 而不仅仅是在函数中。

像这样:

firebase.auth().onAuthStateChanged((user) => {
if (user) {
this.moreinfo=2;
var user2 = firebase.auth().currentUser;
console.log("Current user id:" + user2.uid + "\nMoreinfo:" + this.moreinfo);
} else {
console.log("No user is signed in.");
}
});

关于javascript - *ngIf 上使用的 Angular 4 构造函数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45260053/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com