因此,我有以下代码从Firebase用户列表中检索数据:
currentUserRef: AngularFireList<any>
currentUser: Observable<any>;
var user = firebase.auth().currentUser;
this.currentUserRef = this.af.list('usuarios', ref =>
ref.orderByChild('email').equalTo(user.email));
this.currentUser = this.currentUserRef.valueChanges();
this.currentUser.subscribe(res => console.log(res[0].condominio));
在检索到的数据中,我有两个属性:condominio和email。
在console.log(res [0] .condominio)上我有数据输出到控制台,但我需要将它保存到变量,例如:
userCond: string;
然后我必须从res获取属性'condominio'并将其设置为'userCond',但如果我尝试这样做它不起作用:
this.currentUser.subscribe((res) => { this.userCond = res[0].condominio });
我究竟做错了什么?
"angularfire2": "^5.0.0-rc.11",
"firebase": "^5.3.1",
"ionic-angular": "3.9.2",
编辑:
export class HomePage {
currentUserRef: AngularFireList<any>
currentUser: Observable<any>;
moradorRef: AngularFireList<any>
morador: Observable<any>;
userCond: string;
constructor(
public authService: AuthService,
public userService: UserService,
public navCtrl: NavController,
public navParams: NavParams,
public af: AngularFireDatabase
) {
}
ionViewCanEnter(): Promise<boolean> {
return this.authService.authenticated;
}
ionViewDidLoad(){
debugger;
//TRAZ AS MESMAS INFORMAÇÕES
//this.userService.getCurrentUser();
var user = firebase.auth().currentUser;
//const _this = this;
this.currentUserRef = this.af.list('usuarios', ref =>
ref.orderByChild('email').equalTo(user.email));
this.currentUser = this.currentUserRef.valueChanges();
//this.currentUser.subscribe(res =>
console.log(res[0].condominio));
this.currentUser.subscribe(res => {
debugger;
this.userCond = res[0].condominio;
});
console.log(this.userCond);
this.currentUser.subscribe(res => {
this.userCond = res[0].condominio; // 'this' here refers to the observable, not the class instance
});
要处理这个,请执行:
const _this = this;
this.currentUser.subscribe(res => {
_this.userCond = res[0].condominio;
});
将userCond
定义为Observable。
userCond: Observable<string>;
之后,将condominio
属性值映射到userCond
,同时查询firestore。
this.currentUserRef = this.af.list('usuarios', ref =>
ref.orderByChild('email').equalTo(user.email));
this.userCond = this.currentUserRef.valueChanges()
.pipe(map(res => res[0].condominio));
现在userCond
可以订阅以获得价值,只要有需要。
问题是,您需要在使用类变量userCond
之前等待订阅完成。订阅不是同步,只是您想要在订阅下使用的调用方法。
this.currentUser.subscribe(res => {
this.userCond = res[0].condominio;
this.loopOverAnotherList();
});
loopOverAnotherList() {
// you can use this.userCond here
}