我尝试进行Firebase Angular 5登录,然后尝试打印displayName或前端的任何数据。
auth.service
export class User {
uid: string;
username: string = "";
constructor(auth) {
this.uid = auth.uid
}
}
@Injectable()
export class AuthService {
authState: any = null;
currentUser: User;
constructor(private afAuth: AngularFireAuth,
private db: AngularFireDatabase, private router: Router) {
this.afAuth.authState.switchMap(auth => {
if (auth) {
this.currentUser = new User(auth)
return this.db.object(`/users/${auth.uid}`)
} else return [];
})
.subscribe(user => {
this.currentUser['username'] = user.username
})
}
get currentUsername(): string {
return this.authState['displayName']
}
signUpWithEmail(email: string, password: string, username: string) {
return this.afAuth.auth.createUserWithEmailAndPassword(email, password)
.then((user) => {
user.updateProfile({
displayName : username
});
this.authState = user
this.db.object(`/users/${this.currentUser.uid}`).update({"username": username})
this.isLoggedIn()
})
.catch(error => {
console.log(error)
throw error
});
}
loginWithEmail(email: string, password: string) {
return this.afAuth.auth.signInWithEmailAndPassword(email, password)
.then((user) => {
this.authState = user
this.isLoggedIn()
})
.catch(error => {
console.log(error)
throw error
});
}
isLoggedIn() {
this.afAuth.auth.onAuthStateChanged(auth => {
if (auth) {
console.log(auth);
} else {
console.log('User logged out');
}
});
}
}
login.component
onSignUp(): void {
this.clearErrorMessage()
if (this.email, this.password, this.username) {
this.authService.signUpWithEmail(this.email, this.password, this.username)
.then(() => {
this.router.navigate(['/home'])
})
.catch(_error => {
this.error = _error
this.router.navigate(['/'])
})
}
}
onLoginEmail(): void {
if (this.validateForm(this.email, this.password)) {
this.authService.loginWithEmail(this.email, this.password)
.then(() => this.router.navigate(['/home']))
.catch(_error => {
this.error = _error
this.router.navigate(['/'])
})
}
}
&安培;在我试过的前端 {{authService.currentUsername}} 这是有效的。但只有一次。当我重新加载页面时,控制台告诉我它找不到displayName。 我想知道如何访问currentUser - 或者我可以按照我实现的方式进行操作吗?
答案 0 :(得分:0)
我遇到了同样的问题。这对我有用。
只需使用:
this.angularFireAuth.auth.currentUser
其中angularFireAuth
是
constructor( private angularFireAuth: AngularFireAuth ) {}
它将为您提供本地存储(我相信)登录用户。