如何从 angularfire2 获取当前登录的身份验证状态/用户 [英] How to get currently logged in auth state/user from angularfire2

查看:48
本文介绍了如何从 angularfire2 获取当前登录的身份验证状态/用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 ionic2 应用,正在使用 Firebase 和 angularFire2.我想使用 angularFire2 从 firebase 获取当前的身份验证状态和当前的身份验证对象/用户.

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;
      }
    });

现在我可以在这里设置 localstorage 并缓存我的用户对象以记住身份验证状态.但是,我很想知道如何在不实现自己的自定义本地存储密钥的情况下仅使用 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 文档中列出的示例来呈现模板中的身份验证状态 - 但这给了我一个错误.

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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆