【发布时间】:2018-01-21 09:35:38
【问题描述】:
我正在尝试从 Firebase 数据库中取出项目,但看起来我做不到。
操作符“this”在快照功能中不起作用(在this.authState.prenom = snapshot.val().prenom这一行)
如果我在函数之外执行,它似乎是在函数之前执行的,所以属性是空的。我找到的唯一解决方案是设置一个超时(setTimeout( () => this.authState.prenom = prenom,1000)" 一行,但这不是我想要的。
我只想在快照函数结束后执行声明 this.authState.prenom = prenom; 或以任何方式从该快照函数中获取值。
这是我的文件(变量都已声明)
auth.service.ts 这是构造函数:
constructor(private afAuth: AngularFireAuth,
private db: AngularFireDatabase,
private router:Router) {
this.afAuth.authState.subscribe((auth) => {
this.authState = auth;
if(this.currentUser){
var userId = this.currentUser.uid;
var prenom: any;
var nom: any;
firebase.database().ref('/users/' + userId).on('value',function(snapshot) {
// this.authState.prenom = snapshot.val().prenom; <= This is not working because I can't use "this" operator here and don't know why
console.log(snapshot.val().prenom);
console.log(snapshot.val().nom);
prenom = snapshot.val().prenom;
nom = snapshot.val().nom;
// this.authState.nom = snapshot.val().nom; <= not working because of the operator "this"
});
this.authState.prenom = prenom // <= Not working because it's executed before the snapshot function and don't know why
setTimeout( () => this.authState.prenom = prenom,1000); // <= This is working but setting timeout is not a good thing..
setTimeout( () => this.authState.nom = nom,1000);
// console.log(this.authState.prenom);
}
}
【问题讨论】:
标签: angular typescript firebase firebase-realtime-database angularfire2