Reputation: 1326
profile.page.ts:
username: string;
totalScore: number;
...
loadUserData() {
this.spinnerDialog.show();
this.firebaseServie.loadUserData().then(() => {
this.username = this.sessionData.getUser().getUsername();
this.totalScore = this.sessionData.getUser().getTotalScore();
....
});
firebase.service.ts
:
async loadUserData() {
console.log(this.sessionData.getUser().getEmail());
this.userCollection = this.afs.collection('users', ref => ref.where('email', '==', this.sessionData.getUser().getEmail().toLowerCase()));
this.userDoc = this.afs.collection("users").doc(this.sessionData.getUser().getEmail().toLowerCase());
this.x = this.userDoc.valueChanges().subscribe(((item: User) => {
this.userLoadedUser = item;
console.log("Found user by email id " + this.sessionData.getUser().getEmail() + ":" + this.userLoadedUser.username);
this.sessionData.getUser().setUsername(this.userLoadedUser.username);
this.sessionData.getUser().setTotalScore(this.userLoadedUser.totalScore);
....
}));
}
So how can I be sure that the part in the then()
clause is only executed after we have the data from firebase?
I have edited my question for a better understanding.
Upvotes: 2
Views: 39
Reputation: 775
You could simply return a new Promise in your firebase.service.ts
:
loadUserData() {
return new Promise((resolve, reject) => {
...
this.x = this.userDoc.valueChanges().subscribe(((item: User) => {
...
resolve(); // If everything worked!
}));
...
});
}
I hope that helps!
Upvotes: 1
Reputation: 73301
Since subscribe indicates you're dealing with an observable, better don't start mixing with a promise, but simply use the observable and pipe
otherfunc()
.pipe(map(myfunc))
.subscribe((item:User) => {
});
If you really want the promise, you can convert the observable to a promise.
otherfunc().toPromise().then(myfunc).then(e => {
// runs after
});
Upvotes: 1