简体   繁体   中英

firebase current user id

I am getting an error retrieving current user id from my factory/service. Removing this firebase.auth().currentUser.uid seems to work.
Am I missing something?
Is it possible to get user id from factory?

.factory("dataFire", ["$firebaseArray", "$firebaseAuth", "$firebaseObject", function($firebaseArray, $firebaseAuth, $firebaseObject){
var ref = firebase.database().ref("users/" + firebase.auth().currentUser.uid);
var user = $firebaseObject(ref);
return {
    user: user

} }])

jsfiddle link https://jsfiddle.net/ken19net/m8qkdrpu/37/

Your code that attach the listener to the database, runs before the user is signed in. Since there is no current user at that point firebase.auth().currentUser.uid will throw the following error:

VM603 angular.min.js:118 TypeError: Cannot read property 'uid' of null

In future questions please include the error message, as it would've saved us both some time.

The solution is to attach the listener after the user has been authenticated:

app.controller("appCtrl", function($scope, $firebaseAuth, myService) {

  $scope.signIn = function() {
    $firebaseAuth().$signInAnonymously().then(function(user) {
      var ref = firebase.database().ref("test/" + firebase.auth().currentUser.uid);
    });
  };

});

Note that running your code like above will create a new anonymous user account every time the user loads the page. If that is not what you want, use an auth state listener:

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    var ref = firebase.database().ref("test/" + firebase.auth().currentUser.uid);
  }
});

See the documentation on getting the currently signed in user .

I might of had a similar problem. This might help.

if (firebase.auth().currentUser !== null) {
        console.log("user id: " + firebase.auth().currentUser.uid);

        var ref = firebase.database().ref().child("users/" + firebase.auth().currentUser.uid);

        var syncUserObject = $firebaseObject(ref);
        syncUserObject.$bindTo($scope, "data");

    } else {
        console.log("No user currently logged in");
    }

if all else fails then just JSON.stringify(Object ,null, 2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM