如何从angularfire2获取当前以身份验证状态登录的用户 [英] How to get currently logged in auth state/user from angularfire2
问题描述
我有一个ionic2应用程序,正在使用Firebase和angularFire2.我想使用angularFire2从Firebase获取当前身份验证状态和当前auth对象/用户.
I have an ionic2 app and am using Firebase and angularFire2. I'd like to get the current authentication state and current auth object/user from firebase using angularFire2.
这是到目前为止的工作-我可以验证用户身份并订阅FirebaseAuthState以获取facebook用户对象.
Here's what's working so far - I can authenticate the user and subscribe to the FirebaseAuthState to get the facebook user object.
constructor(platform: Platform, private auth: FirebaseAuth) {
auth.subscribe((user: FirebaseAuthState) => {
if (user) {
// I could store user in localstorage, but I'd like to see an All Firebase solution
this.rootPage = TabsPage;
} else {
this.rootPage = LoginPage;
}
});
现在,我可以在此处设置本地存储并缓存我的用户对象以记住身份验证状态.但是,我很好奇只能在不实现自己的自定义本地存储密钥的情况下才能使用Firebase.我看到Firebase存储了它自己的localStorage密钥,因此知道它已登录.
Now I can just set localstorage here and cache my user object to remember auth state. However, I am curious to see how I can use Firebase only without me implementing my own custom local storage key. I see that Firebase stores a localStorage key of it's own so knows that its logged in.
如何从代码获取auth对象?此外,我尝试了AngularFire2文档中列出的示例,以在模板中呈现auth状态-但这给了我一个错误.
How can I get the auth object from code? Additionally, I tried the listed example in the AngularFire2 documentation to render the auth state in the template - but that gives me an error.
import {FirebaseAuth} from 'angularfire2';
@Component({
selector: 'auth-status',
template: `
<div *ng-if="auth | async">You are logged in</div>
<div *ng-if="!(auth | async)">Please log in</div>
`
})
class App {
constructor (@Inject(FirebaseAuth) public auth: FirebaseAuth) {}
}
推荐答案
当前身份验证状态可从注入的 FirebaseAuth
中获得.您可以获取实际的身份验证数据 auth.getAuth()
current authentication state is available from the injected FirebaseAuth
. You can get the actual auth data auth.getAuth()
请参阅: https://github.com/angular/angularfire2/blob/master/src/providers/auth.ts#L99
这篇关于如何从angularfire2获取当前以身份验证状态登录的用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!