cplus
cplus

Reputation: 1115

AngularJS Firebase sendEmailVerification not working

I want to send a verification email to the registering user using Firebase.

My registration controller is like the following:

app.controller("MyregisterCtrl", ["$scope", "firebase", "$firebaseAuth", "$location", function ($scope, firebase, $firebaseAuth, $location) {

    $scope.signUp = function () {
        var username = $scope.user.email;
        var password = $scope.user.password;


        if (username && password) {
            var auth = $firebaseAuth();
            var user = firebase.auth().currentUser;

            auth.$createUserWithEmailAndPassword(username, password)
            user.sendEmailVerification()
                .then(function () {
                    console.log("User signup success");
                    $scope.errMsg = false;
                    $location.path('/login.signin');
                }).catch(function (error) {
                $scope.errMsg = true;
                $scope.errorMessage = error.message;
            });
        }
    }

}]);

The user gets registered in the Firebase user database. But I have to click three times in a row on the submit button in order to get a verification email. Very strange.

Why doesn't it send it on the first submit click?

Here is the error screenshot:

enter image description here

Upvotes: 0

Views: 725

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

Creating a user account is an operation that can take some time. If you call sendEmailVerification() before the operation is completed, you'll get the error message in your screenshot (for any future questions: don't post pictures of text please, post the actual text itself).

To solve the problem, you can wait until the account is created by waiting for the so-called promise to resolve:

auth.$createUserWithEmailAndPassword(username, password)
    .then(function(user) {
        user.sendEmailVerification()
    }).then(function () {
        console.log("User signup success");
        $scope.errMsg = false;
        $location.path('/login.signin');
    }).catch(function (error) {
        $scope.errMsg = true;
        $scope.errorMessage = error.message;
    });

So the sequence here:

  1. create the user account
  2. once this succeeds, send a verification email
  3. once this succeeds, log success and redirect
  4. if either 1 or 2 fails, show an error message

Upvotes: 2

Related Questions