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);
....
}));
}
那么如何确定then()
子句中的部分仅在从Firebase获得数据后才执行?
为了更好的理解,我已经对问题进行了编辑。
答案 0 :(得分:1)
由于订阅表明您正在处理一个可观察的对象,因此最好不要开始与一个承诺混为一谈,而只需使用可观察的对象和pipe
otherfunc()
.pipe(map(myfunc))
.subscribe((item:User) => {
});
如果您确实想要诺言,则可以将可观察者转换为诺言。
otherfunc().toPromise().then(myfunc).then(e => {
// runs after
});
答案 1 :(得分:1)
您只需在firebase.service.ts
中返回一个新的Promise:
loadUserData() {
return new Promise((resolve, reject) => {
...
this.x = this.userDoc.valueChanges().subscribe(((item: User) => {
...
resolve(); // If everything worked!
}));
...
});
}
希望对您有帮助!