我的Angular,Firebase(和Ionic)应用程序出现问题。每当用户登录时,我都会在侧菜单中自动更改内容,显示其姓名和照片以及其他链接(例如,删除登录链接)。
这是我的代码的相关部分:
app.component.html:
<ion-app>
<ion-split-pane when="lg">
<ion-menu>
<ion-content class="menu-content">
<ion-list class="menu-list">
<h3 *ngIf="user" class="center">{{user.first_name}} {{user.last_name}}</h3>
<div *ngIf="!user" style="margin-top: 10px">
<ion-item tappable button (click)="gotoPage('/login')">
<ion-icon name="log-in" slot="start"></ion-icon>
{{"LOG_IN" | translate}}
</ion-item>
<ion-item tappable="" button (click)="gotoPage('/signup')">
<ion-icon name="add" slot="start"></ion-icon>
{{"SIGN_UP" | translate}}
</ion-item>
</div>
<!--other menus-->
</ion-list>
</ion-content>
</ion-menu>
<ion-router-outlet main></ion-router-outlet>
</ion-split-pane>
</ion-app>
app.component.ts:
@Component({
selector: 'app-root',
templateUrl: 'app.component.html'
})
export class AppComponent {
user: any = null;
constructor(
public fAuthService: FirebaseAuthService,
public firebaseService: FirebaseService,
) {
this.initializeApp();
}
initializeApp() {
this.fAuthService.userObs.subscribe((user) => {
console.log("observed user: " + user);
if(!user) {
this.user = null;
return null;
}
this.firebaseService.getUserData(user.uid).then(userData => {
this.user = userData.data();
}, error => console.log(error, "getUserData in app.component"));
});
}
}
firebase-auth.service.ts
export class FirebaseAuthService {
userObs = this.afAuth.authState;
currentAuthState = false;
currentUserData = null;
constructor( public afAuth: AngularFireAuth, public afs: AngularFirestore ){
this.userObs.subscribe((user) => {
this.currentAuthState = !!user;
if (user) {
this.afs.collection('/users').doc(user.uid).ref.get().then(
res => {
this.currentUserData = res.data();
}
);
}
else {
this.currentUserData = null;
}
});
}
doRegister(value) {
return new Promise<any>((resolve, reject) => {
firebase.auth().createUserWithEmailAndPassword(value.email, value.password)
.then(res => {
console.log(res);
resolve(res);
}, err => reject(err));
});
}
doLogin(value) {
return new Promise<any>((resolve, reject) => {
firebase.auth().signInWithEmailAndPassword(value.email, value.password)
.then(res => {
resolve(res);
}, err => reject(err));
});
}
doLogout() {
return new Promise((resolve, reject) => {
if (firebase.auth().currentUser){
this.afAuth.auth.signOut();
resolve();
}
else {
reject();
}
});
}
}
问题是,有时(很少,而且经常是第一次尝试)菜单似乎没有注意到用户已连接,对它的userObs.subscribe
没有反应。
此外,如果我确实更改了用户数据中的某些内容,我希望它自动重新加载。因此,我正在考虑“触发”可观察的userObs
,以便其订阅者可以重做相关代码。
所以有两个问题: -为什么菜单不总是重新加载?比赛条件? -如何强制触发此重新加载/刷新可观察到的?