I am truly perplexed as to why the variables aren't holding their values.
I've declared a variable user and initialized it with data from the userData() function. However, it appears as undefined when I log it within the constructor as well as in the ProfilePage.
https://i.sstatic.net/L1w17.png
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 attempted to find solutions by researching similar issues such as this one. It seems that the problem lies in Angular's asynchronous nature, leading me to explore concepts like promises as suggested in posts like this. There was also mention of using .then().
Despite my efforts to implement these suggestions in my specific case, I encountered various syntax errors.
Your guidance would be greatly appreciated.