I am very confused as to why the variables is not holding.
I have a variable user which is assigned with the data in userData(). But it's undefined when console log within the constructor and ProfilePage.
share-service.ts
export class ShareService {
uid: string;
user;
constructor(public db: AngularFireDatabase) {
let currentUser = firebase.auth().currentUser;
this.uid = currentUser.uid;
this.userData();
console.log('[constructor]user: ', this.user);
}
userData() {
this.db.object(`users/${this.uid}`).snapshotChanges().subscribe(data => {
this.user = data.payload.val();
console.log('[userData]user: ', this.user);
});
}
getUser() {
return this.user;
}
}
profile.ts
export class ProfilePage {
user;
constructor(public navCtrl: NavController, public firebaseService: FirebaseService, shareService: ShareService) {
console.log('[profile.ts]', shareService.getUser());
}
}
- "angularfire2": "5.0.0-rc.4",
- "firebase": "4.8.2",
- "ionic-angular": "3.9.2",
- "rxjs": "^5.5.6",
- "@ionic/app-scripts": "3.1.8",
- "typescript": "2.4.2"
I have already tried searching for similar questions like for example this and read that it has something to do with how angular is asynchronous and then upon further investigation I read that promise is needed like this. I also read somewhere that .then() should be used.
I tried several ways to implement those into this use case scenario but all turned out with syntax errors.
In need of advice, please.