如何在AngularFire2中获取firebase.User [英] How to get the firebase.User in AngularFire2
问题描述
我正在使用AngularFire2(Ionic2)和Firebase身份验证.
I am using AngularFire2 (Ionic2) and Firebase Authentication.
我在尝试获取当前用户时遇到问题.适用于我,但不一致.有时填充,有时为null.
I am having a problem trying to get the current user. The works for me, but inconsistently. Sometimes it is populated, and sometimes it is null.
let user: firebase.User = firebase.auth().currentUser;
有没有办法使当前用户更加一致?
Is there a way to get the current user more consistently?
更多信息:
我登录如下:
import { FirebaseAuth, AuthProviders, AuthMethods } from 'angularfire2';
public auth: FirebaseAuth
this.auth.login({
provider: AuthProviders.Google,
method: AuthMethods.Popup
}).then((data: any) => {
this.fireAuth.onAuthStateChanged((user) => {
....
});
});
此处始终填充用户.但是我需要访问用户的地方是代码的另一部分.
Here the user is always populated. But where I need to get access to the user, is in another part of the code.
任何帮助表示赞赏.
更新
我尝试使用以下命令获取当前用户:
I try use the following to get the current user:
this.auth.subscribe((authData) => {
let user = authData.auth;
credential = firebase.auth.GoogleAuthProvider.credential(googleIdToken, googleAccessToken);
user.reauthenticate(credential).then(() => {...
});
但是当我尝试创建凭据时,出现以下错误:
But then when I try create the credentials, I get the following error:
例外:未捕获(承诺中):错误:重新验证失败:第一 参数凭据"必须是有效的凭据.
EXCEPTION: Uncaught (in promise): Error: reauthenticate failed: First argument "credential" must be a valid credential.
使用第一种方法获取当前用户后,我没有任何错误,并且可以正常工作.
When I get the current user in the first method, I don't get any errors and it works.
更多信息:
当我console.log
以下user
对象时,它们看起来都相同:
When I console.log
the following user
objects, they both look identical:
let user: firebase.User = this.fireAuth.currentUser;
console.log(user);
和
this.auth.subscribe((authData) => {
let user: firebase.User = authData.auth;
console.log(user);
});
但其中一个有效(当不为null时),而另一个无法重新认证.
but the one works (when not null) and the other cannot reauthenticate.
推荐答案
请注意,这里有一个新的AngularFire版本. (4.0.0)
Attention there is a new AngularFire Version. (4.0.0)
在新版本中,所有模块均被拆分.也就是说,您需要使用AngularFireAuth
In the new version all the modules are split up. That means, you need to use the AngularFireAuth
constructor(afAuth: AngularFireAuth) {
afAuth.authState.subscribe(auth => {
if(auth) {
console.log('logged in');
} else {
console.log('not logged in');
}
});
}
希望我能帮忙
这篇关于如何在AngularFire2中获取firebase.User的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!