0

I´m new with Firebase. I´m developing an angular + firebase app where after user has been registered with email + password, he can save his username after submit a profile form.

Before it, I want to know if any user in the application has the username submitted. This aproch doesnt work because scope.used is always false:

       scope.used = false;

        scope.updateProfile = function(profile) {
            var ref = new Firebase(FIREBASE_URL + '/users');
            ref.orderByChild("username").equalTo(profile.username).on("child_added", function(snapshot) {
                if (currentUser != snapshot.key()) {
                    scope.used = true;
                }   
            }); 

            if (scope.used) {
                console.log('username already exists');
            }   
        };  

Is there another way to accomplish it?

EDIT (I answer to myself)

This approach works:

        scope.used = false;
        var userRef = new Firebase(FIREBASE_URL + '/users/' + currentUser);


        scope.updateProfile = function(profile) {

            var ref = new Firebase(FIREBASE_URL + '/users');

            ref.orderByChild("username").equalTo(profile.username).on("child_added", function(snapshot) {
                if (currentUser != snapshot.key()) {
                    scope.used = true;
                }   
            }); 

            ref.orderByChild("username").equalTo(profile.username).once("value", function(snap) {
                //console.log("initial data loaded!", Object.keys(snap.val()).length === count);
                if (scope.used) {
                    console.log('username already exists');
                    scope.used = false;
                }else{
                    console.log('username doesnt exists, update it');
                    userRef.child('username').set(profile.username);
                }   
            }); 
        };  
Lorraine
  • 441
  • 5
  • 23
  • 1
    See http://stackoverflow.com/questions/29970681/enforcing-unique-usernames-with-firebase-simplelogin?rq=1. You might also want to add your solution as a self-answer. – Frank van Puffelen Feb 26 '16 at 09:08
  • Ok, i did it but, can you explain me or pass me any link where explain why like in this case, scope.used is shared between both methods? – Lorraine Feb 26 '16 at 17:15

0 Answers0