When working with my Angular2 component, I encountered a situation where I needed to store a value from Firebase into a variable inside the constructor. Like so:
this.dbAction.getDB().take(1).subscribe(data => {
this.userVisitOrder = data[0][this.currentUserID]['settings']['visitOrder'];
console.log(this.userVisitOrder); // Value exists
});
Interestingly, I needed to use this variable in constructing an Observable to access specific Firebase data. However, I faced an issue within my constructor:
this.visitsRef = afDatabase.list('data/users/' + this.currentUserID + '/visits/', ref => ref.orderByChild(this.userVisitOrder)); // Here the value is undefined
It seems like an asynchronous problem, but how can I make sure to access the data stored in my variable?
Describing the getDb()
function in my dbAction
Service:
getDB() {
return this.afDatabase.list(`data`).valueChanges().map((data) => data);
}
Attempting to combine the codes by putting the second code snippet within the first:
this.dbAction.getDB().take(1).subscribe(data => {
this.userVisitOrder = data[0][this.currentUserID]['settings']['visitOrder'];
this.visitsRef = afDatabase.list('data/users/' + this.currentUserID + '/visits/', ref => ref.orderByChild(this.userVisitOrder));
this.visits = this.visitsRef.snapshotChanges().map(changes => {
return changes.map(c => ({ key: c.payload.key, ...c.payload.val() }));
});
});
This led to a console error as depicted below: