Firebase creates custom object from auth data

So I am using Angularfire in an ionic app and am trying to figure out how to create a user object associated with auth data from an Auth $ createUser call. My first attempt was triggered by an autoresponder and the user got authenticated, then a custom object was created and placed in $firebaseArray

, which works great, but I don't know how to grab the current user after they are logged in to update, kill, or do whatever - or with these user data. I made it work with a loop through the users array and map the uid to the custom array element and the elementauth.uid

which was configured the same as in creating the user array object. It seems really inefficient to get stuck in a loop if there is a large array of users and needs to be done across multiple pages.

My current attempt is using a different method:

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 is the service that the controller uses:

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 have no reliable reference to the current data of the user objects from the array. Object IDs are stored only in the controller area.

I have looked at other posts but they all used old firebase versions with deprecated methods.

+1


source to share


1 answer


If you store items with a "natural key", it is best to store them under that key. For users it will be 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 will notice that I am using non-AngularFire child()

and set()

. AngularFire is built on top of the regular Firebase SDK, so they work well with each other. The advantage of this is that you can use the full power of the Firebase JavaScript SDK and only use AngularFire, which is best for that: wire things to Angular $scope

.

Saving user data is explained in the Firebase JavaScript tutorial . We also store them underneath them uid

, rather than using them push()

, which means $add()

behind the scenes.

+1


source







All Articles