由于某种原因,我无法在typescript foreach循环
中收到给定的元素值constructor(db: AngularFireDatabase) {
}
this.fbUserData = this.db.list('users/'+this.userid).valueChanges()
this.fbUserData.forEach(element => {
this.currentRole = element[2].toString(); // receive value
})
现在在循环之外我想从AngularFireBase接收值 我尝试了以下方法:
this.userid = this.firebaseAuth.auth.currentUser.uid.toString();
this.fbUserData = this.db.list('users/'+this.userid).valueChanges()
this.fbUserData.forEach(element => {
this.rolelist.push(element[2].toString());
})
但是this.rolelist(数组)在循环外仍然是空的。在循环内部,它将接收像array ['test']
这样的值我希望它在循环外的console.log中像这样:
checkAuth(data){
this.userid = this.firebaseAuth.auth.currentUser.uid.toString();
this.fbUserData = this.db.list('users/'+this.userid).valueChanges()
this.fbUserData.forEach(element => {
this.rolelist.push(element[2].toString());
})
console.log(this.rolelist);
这样this.rolelist具有来自foreach循环的元素值
答案 0 :(得分:0)
您的firebase调用返回Observable =>您必须.subscribe()
到this.fbUserData
才能访问该值
this.fbUserData.subscribe(userData => {});
每次数据以新数据作为参数更改时,都会调用subscribe内部的函数。如果您不想要更新,可以this.fbUserData.first().subscribe(userData => {});
您可能需要import 'rxjs/add/operator/first';
才能使其正常工作