【问题标题】:Firebase make user object from auth dataFirebase 从身份验证数据中创建用户对象
【发布时间】:2015-08-05 03:12:28
【问题描述】:

所以我在 ionic 应用程序中使用 Angularfire,并试图弄清楚如何创建一个与来自 Auth $createUser 调用的身份验证数据相关联的用户对象。我的第一次尝试进行了 auth 调用并且用户通过了身份验证,然后创建了一个用户对象并将其推送到 $firebaseArray 工作正常,但我不知道如何在他们登录后获取当前用户进行更新,破坏,或对用户数据做任何事情。我已经使它与遍历用户数组并匹配用户数组项中的 uid 和在用户数组对象创建中设置为相同的auth.uid 项一起工作。如果有一个很大的用户数组并且需要在多个页面上完成,这似乎真的没有效率。

我目前的尝试是使用不同的方法,如下所示:

angular.module('haulya.main')
.controller('RegisterController', ['Auth', '$scope', 'User', '$ionicPlatform', '$cordovaCamera','CurrentUserService',
  function(Auth, $scope, User, $ionicPlatform, $cordovaCamera, CurrentUserService) {

  //scope variable for controller
  $scope.user = {};
  console.log(User); 

  $scope.createUser = function(isValid) {

    var userModel;
    $scope.submitted = true;

    //messages for successful or failed user creation
    $scope.user.message = null;
    $scope.user.error = null;

    //if form is filled out valid
    if(isValid) {

      //Create user with email and password firebase Auth method
      Auth.$createUser({
        email: $scope.user.email,
        password: $scope.user.password
      })
      .then(function(userData) {

        userModel = {
          uid: userData.uid,
          photo: $scope.user.photo || null,
          firstName: $scope.user.firstName,
          lastName: $scope.user.lastName,
          email: $scope.user.email,
          cell: $scope.user.cell,
          dob: $scope.user.dob.toString(),
          city: $scope.user.city,
          state: $scope.user.state,
          zip: $scope.user.zip
        }

        // add new user to profiles array
        User.create(userModel).then(function(user) {
          $scope.sharedUser = User.get(user.path.o[1]);
        });


        $scope.user.message = "User created for email: " +  $scope.user.email;
      })
      .catch(function(error) {
        //set error messages contextually
        if(error.code == 'INVALID_EMAIL') {
          $scope.user.error = "Invalid Email";
        }
        else if(error.code == 'EMAIL_TAKEN'){
          $scope.user.error = "Email already in use, if you think this is an error contact an administrator";
        }
        else {
          $scope.user.error = "Fill in all required fields";
        }
      });
    }


  };


  //Get profile pic from camera, or photo library
  $scope.getPhoto = function(type) {
    $ionicPlatform.ready(function() {
      //options for images quality/type/size/dimensions
      var options = {
        quality: 65,
        destinationType: Camera.DestinationType.DATA_URL,
        sourceType: Camera.PictureSourceType[type.toUpperCase()],
        allowEdit: true,
        encodingType: Camera.EncodingType.JPEG,
        targetWidth: 100,
        targetHeight: 100,
        popoverOptions: CameraPopoverOptions,
        saveToPhotoAlbum: false
      };

      //get image function using cordova-plugin-camera 
      $cordovaCamera.getPicture(options)
      .then(function(photo) {
        $scope.user.photo = photo;
      }, function(err) {
        console.log(err);
      });
    });

  };

}]);

这是控制器正在使用的服务:

angular
  .module('haulya.main')
  .factory('User', function($firebaseArray) {
    var ref = new Firebase('https://haulya.firebaseio.com');
    var users = $firebaseArray(ref.child('profiles'));

    var User = {
      all: users,
      create: function(user) {
        return users.$add(user);
      },
      get: function(userId) {
        return $firebaseArray(ref.child('profiles').child(userId));
      },
      delete: function(user) {
        return users.$remove(user);
      } 
    };

    return User;
});

这也有效,但我再次没有对数组中当前登录的用户对象数据的可靠引用。对象 id 仅存储在控制器范围内。

我查看了其他帖子,但他们都使用旧版本的 firebase 和不推荐使用的方法。

【问题讨论】:

    标签: authentication firebase angularfire


    【解决方案1】:

    如果您要存储具有“自然键”的项目,最好将它们存储在该键下。对于用户,这将是uid。

    所以不要用$add() 存储它们,而是用child().set() 存储它们。

    create: function(user) {
      var userRef = users.$ref().child(user.uid);
      userRef.set(user);
      return $firebaseObject(userRef);
    }
    

    您会注意到我正在使用非 AngularFire 方法 child() 和 set()。 AngularFire 构建在 Firebase 的常规 JavaScript SDK 之上,因此它们可以很好地互操作。这样做的好处是您可以使用 Firebase JavaScript SDK 的所有功能,并且只将 AngularFire 用于它最擅长的事情:将事物绑定到 Angular 的 $scope。

    Storing user data is explained in Firebase's guide for JavaScript。我们也将它们存储在他们的uid 下,而不是使用push(),这是$add() 在幕后调用的。

    【讨论】:

    • 谢谢,我想这就是我要找的!我一直在用头撞墙试图得到这个。我没有意识到你也可以使用常规的 javascript sdk 东西,所以我从来没有花时间去研究它。我现在肯定会这样做。这是我第一次使用 firebase,刚刚加入。再次感谢!
    • 不客气,迈克。我会看看我们是否可以在文档中使互操作性更清晰。但在那之前,我会很乐意一次又一次地解释它。 :-) 如果您有任何其他问题,请发布问题!
    • 太棒了。再次感谢您的完美工作,感谢您提供的出色产品!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-05
    • 2021-06-29
    • 2020-06-10
    • 2019-03-28
    • 1970-01-01
    • 2021-12-19
    相关资源
    最近更新 更多