Angularfire2 身份验证:如何获取当前用户?
Angularfire2 Authentication: How to get the current user?
在我的 angular-app 中,我使用 angularfire2 身份验证。
打开某个window时,想获取当前用户的邮箱
为此,我写了如下代码:
ngOnInit() {
this.currentUserEmail = this.angularFireAuth.authState
.switchMap(user => {
console.log("this is a test");
return user.email;
});
}
代码遵循此处的文档:
https://angularfirebase.com/lessons/google-user-auth-with-firestore-custom-data/#Step-3-Auth-Service
但是,由于某种原因,"switchMap" 之后的部分从未输入过”。
所以行 "this is a test" 永远不会被打印出来。
如何获取当前用户(和 his/her 电子邮件)?
这应该可以正常工作。
constructor(public afAuth: AngularFireAuth){}
this.afAuth.auth.onAuthStateChanged(user => {
if (user) {
// logged in or user exists
}
else {
// not logged in
}
})
注意:在上面,每次授权状态发生变化(登录,注销)时都会触发
获取用户的另一种方式:
this.afAuth.authState.subscribe(user => {
if (user){
}
else{
}
})
您还可以获得另一个用户数据。如需电子邮件,您可以致电 'user.email'
在我的 angular-app 中,我使用 angularfire2 身份验证。 打开某个window时,想获取当前用户的邮箱
为此,我写了如下代码:
ngOnInit() {
this.currentUserEmail = this.angularFireAuth.authState
.switchMap(user => {
console.log("this is a test");
return user.email;
});
}
代码遵循此处的文档: https://angularfirebase.com/lessons/google-user-auth-with-firestore-custom-data/#Step-3-Auth-Service
但是,由于某种原因,"switchMap" 之后的部分从未输入过”。 所以行 "this is a test" 永远不会被打印出来。
如何获取当前用户(和 his/her 电子邮件)?
这应该可以正常工作。
constructor(public afAuth: AngularFireAuth){}
this.afAuth.auth.onAuthStateChanged(user => {
if (user) {
// logged in or user exists
}
else {
// not logged in
}
})
注意:在上面,每次授权状态发生变化(登录,注销)时都会触发
获取用户的另一种方式:
this.afAuth.authState.subscribe(user => {
if (user){
}
else{
}
})
您还可以获得另一个用户数据。如需电子邮件,您可以致电 'user.email'