shabany
shabany

Reputation: 849

AngularFire (Angular + Firebase) Authentication Error delay

I found out something weird. Please help!

$scope.login = function() {
    ref.authWithPassword({
        email: $scope.user.email,
        password: $scope.user.password
    }, function(error, authData) {
        if (error) {
            console.log("Login Failed!", error);
            $scope.message = error.toString();
        } else {
            $location.path('/meetings');
            console.log("Authenticated successfully with payload:", authData);
        }
    });
} //login

This is a login function and it works nicely.However, the thing is that I get error 3, 4 sec after I have submitted the login. I noticed that my {{message}} is not being updated immediately after I receive value at $scope.message . I thought Angular should show that value as soon as it changes. ?

After I click for the second time, I get the error showed.

This is where I am printing the value:

<p class="error formerror" ng-show="message">{{message}}</p>

Upvotes: 0

Views: 335

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599011

You're calling authWithPassword, which is part of Firebase's regular JavaScript SDK. This API will start the authentication process and call your function when the authentication completes. Unfortunately at that point AngularJS is no longer aware of any updates you make to $scope.

To make AngularJS aware of the update, wrap your code in a $timeout call:

$scope.login = function() {
    ref.authWithPassword({
        email: $scope.user.email,
        password: $scope.user.password
    }, function(error, authData) {
        $timeout(function() {
            if (error) {
                console.log("Login Failed!", error);
                $scope.message = error.toString();
            } else {
                $location.path('/meetings');
                console.log("Authenticated successfully with payload:", authData);
            }
        });
    });
} //login

Note that precisely for this reason, AngularFire provides convenience wrappers around these authentication functions in its $firebaseAuth service. See the section in the AngularFire guide on logging users in.

The wrapper function you're looking for is $authWithPassword, read a sample of how to use $authWithPassword in its API documentation.

Upvotes: 1

Related Questions