【问题标题】:angularjs rootscope user database info from firebase来自firebase的angularjs rootscope用户数据库信息
【发布时间】:2017-03-12 02:18:21
【问题描述】:

我正在尝试从用户的数据库中获取用户信息并使用 rootscope 从任何地方访问它。
我在用户登录时获取用户的电子邮件和 uid。
但是,要从数据库中获取用户的信息,我需要调用我的数据库并一一读取信息并将其作为变量存储在 rootscope 中以便从任何地方访问它。

所以,我的问题如下:

  • 如何在本例中使用 rootscope?
  • 有没有更好的方法来做到这一点?
  • 在下面的示例中,控制台日志显示了名字,但我不知道如何对其进行根范围检查?

感谢您的帮助。

app.run(['$rootScope', '$state', '$stateParams', '$cookies', "$location",
function ($rootScope, $state, $stateParams, $cookies, $location) {

    firebase.auth().onAuthStateChanged(function(user) {
        if (user) {

            $rootScope.user.uid = user.uid;
            $rootScope.user.email = user.email;

            return firebase.database().ref('/users/' + user.uid).once('value').then(function(snapshot) {

                var firstname = snapshot.val().firstname;
                console.log("first name", firstname);

            });
        } else {
            // No user is signed in.
        }
    });
}]);

【问题讨论】:

    标签: angularjs firebase firebase-realtime-database firebase-authentication


    【解决方案1】:

    如果您使用 AngularFire 始终使用其包装方法与原生 firebase 方法。

    不要使用

    firebase.auth().onAuthStateChanged
    firebase.database().ref('/users/' + user.uid).once('value')
    

    使用

    $firebaseAuth().$onAuthStateChanged
    var userData = $firebaseObject(firebase.database().ref('/users/' + user.uid));
    

    查看以下链接以获取angularFire 中可用方法的完整列表。 https://github.com/firebase/angularfire/blob/master/docs/reference.md

    我建议像这样修改您的代码。

    $firebaseAuth().$onAuthStateChanged(function(user) {
        if (user) {
          $rootScope.user = $firebaseObject(firebase.database().ref('/users/' + user.uid));
          $rootScope.user.uid = user.uid;
          $rootScope.user.email = user.email;
          console.log("Here you should have complete user object");
          // still if you want to do something when user is loaded
          /* $rootScope.user.$loaded(function(loadedUser) {
                var firstname = loadedUser.firstname;
                console.log("first name", firstname);
            });*/
        } else {
            // No user is signed in.
        }
    });
    

    当然你需要使用依赖注入来包含$firebaseObject$firebaseAuth

    【讨论】:

      【解决方案2】:

      有两种方法可以满足您的需求

      方法一:

      您可以这样做$rootScope.authData=user;,然后通过注入$rootScope 从任何地方访问它。但问题是当您刷新页面时$rootScope 将为空检查此SO Question

      方法2:

      我更喜欢这种方法,你可以使用angularfire$getAuth()函数,$getAuth是同步函数,它会给你当前的用户数据。

      var myUser=$scope.AuthObj.$getAuth();
      

      more detail check this

      【讨论】:

      • 能否请您写一个完整的答案以及如何使其适应我的代码?我有点困惑。
      • 您使用的是哪个版本的 firebase
      • 知道了,您可以在任何控制器中写入var myUser=$firebaseAuth().$getAuth(); 以获取登录用户信息。
      猜你喜欢
      • 1970-01-01
      • 2022-12-08
      • 1970-01-01
      • 2018-01-07
      • 2018-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多