登录有效,但是当我尝试访问uid时,它返回null。我在控制台看过uid。我似乎无法将其从我的服务中解脱出来。以下是我的AuthService的相关部分:
@Injectable()
export class AuthService {
uid: any = null;
constructor(private _firebaseAuth: AngularFireAuth, private router: Router) {
this._firebaseAuth.auth.onAuthStateChanged(function(user) {
if (user) {
this.uid = user.uid;
}
});
signInAnonymously() {
return this._firebaseAuth.auth.signInAnonymously().catch(function(error) {
const errorCode = error.code;
const errorMessage = error.message;
console.log(errorCode, errorMessage);
});
}
在我的组件中,我在点击按钮上调用signInAnonymously():
onGuestClick() {
let uid: any = null;
const guestSignIn = this.authService.signInAnonymously().then(() => {
uid = this.authService.uid;
console.log(uid); // returns null
this.toggleOnline(uid);
});
}
身份验证状态正在发生变化,但我的uid没有更新,或者至少在我发号子之前没有更新。我需要在除服务构造函数之外的其他地方调用AuthStateChanged吗?我做错了什么?