简体   繁体   中英

Firebase make user object from auth data

So I'm using Angularfire in an ionic app and trying to figure out how to make a user object that is associated with the auth data from an Auth $createUser call. My first try had the auth call and the user got authenticated, then a user object was made and pushed into a $firebaseArray which works fine, but I don't know how to grab the current user after they are logged in to update, destory, or do anything with that users data. I have made it work with looping through the users array and matching the uid from the user array item and the auth.uid item which was set to be the same in the user array object creation. This seems really ineffecient to loop over if there is a large user array and it needs to be done on multiple pages.

My current attempt is using a different method like so:

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

  };

}]);

And here's the service the controller is using:

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

This also works, but again I don't have a solid reference to the currently logged in users object data from the array. The objects id is only stored on the controllers scope.

I looked through other posts, but they were all using older versions of firebase with deprecated methods.

If you're storing items that have a "natural key", it is best to store them under that key. For users this would be the uid .

So instead of storing them with $add() , store them with child().set() .

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

You'll note that I'm using non-AngularFire methods child() and set() . AngularFire is built on top of Firebase's regular JavaScript SDK, so they interoperate nicely. The advantage of this is that you can use all the power of the Firebase JavaScript SDK and only use AngularFire for what it's best at: binding things to Angular's $scope .

Storing user data is explained in Firebase's guide for JavaScript . We store them under their uid there too instead of using push() , which is what $add() calls behind the scenes.

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