AngularFire2 在检索数据后访问数据
AngularFire2 access data after retrieve it
我正在尝试使用 AngularFire2 从我的 Firebase 获取数据。
我想查看具体的数据,从Firebase获取这些数据后,我只能在特定的范围内查看,而不是在对Firebase进行操作之后。为什么会这样?
下面是我的代码:
this.af.database.list('/users/1qfcMAQnglX9jsW5GdLpPko1HqE2', { preserveSnapshot: true})
.subscribe(snapshots=>{
snapshots.forEach(snapshot => {
if(snapshot.key=="reg_boolean"){
console.log(snapshot.val());
this.bo=snapshot.val();
}
this.currentUser.push({key:snapshot.key,value:snapshot.val()});
console.log(this.currentUser);
//console.log(snapshot.key, snapshot.val());
if(this.bo==true){console.log("happy"); }; //i can access only in this scope
});
})
if(this.bo==true){console.log("happy"); }; //why i can access this value??it's undefined, this happen before the subscribe with angularfire2
未定义,因为 this.af.database.list
它是异步的,因此 subscribe
中的代码将在 this.af.database.list
检索数据时执行。所以当代码到达行时 if(this.bo==true){console.log("happy"); };
它什么都没有,因为订阅根本没有完成。
订阅就像旧的承诺,但现在它与 rxjs 一起工作我建议你学习它,因为 angular 并且 ionic 非常关注它。
我正在尝试使用 AngularFire2 从我的 Firebase 获取数据。 我想查看具体的数据,从Firebase获取这些数据后,我只能在特定的范围内查看,而不是在对Firebase进行操作之后。为什么会这样?
下面是我的代码:
this.af.database.list('/users/1qfcMAQnglX9jsW5GdLpPko1HqE2', { preserveSnapshot: true})
.subscribe(snapshots=>{
snapshots.forEach(snapshot => {
if(snapshot.key=="reg_boolean"){
console.log(snapshot.val());
this.bo=snapshot.val();
}
this.currentUser.push({key:snapshot.key,value:snapshot.val()});
console.log(this.currentUser);
//console.log(snapshot.key, snapshot.val());
if(this.bo==true){console.log("happy"); }; //i can access only in this scope
});
})
if(this.bo==true){console.log("happy"); }; //why i can access this value??it's undefined, this happen before the subscribe with angularfire2
未定义,因为 this.af.database.list
它是异步的,因此 subscribe
中的代码将在 this.af.database.list
检索数据时执行。所以当代码到达行时 if(this.bo==true){console.log("happy"); };
它什么都没有,因为订阅根本没有完成。
订阅就像旧的承诺,但现在它与 rxjs 一起工作我建议你学习它,因为 angular 并且 ionic 非常关注它。