Search code examples
javascriptangularjsfirebase-authenticationangularjs-service

angularjs firebase user auth service not communicating with the views


I have a service which passes on the parameter pseudonym to the evironment. I call on this pseudonym in my views, but it doesn't appear at all.
How can I fix this to display the value in my views?

MyUser service:

app.service('MyUser', ['DatabaseRef', 'firebase', function(DatabaseRef, firebase) {
    var pseudonym ="";
    var userId = firebase.auth().currentUser.uid;

    return {
        pseudonym: function() {
            DatabaseRef.ref('/users/' + userId).once('value')
                .then(function (snapshot) {
                    pseudonym = snapshot.val().pseudonym;
                    console.log("pseudony: ", pseudonym);
                    return pseudonym;
                });

        }
    }
}]);

in my console, I see the value for the pseudonym. but not in my view html using {{pseudonym}}
and here is the example view controller:

app.controller('ExampleCtrl', ["MyUser",
    function (MyUser) {
     $scope.pseudonym = MyUser.pseudonym();
}]);

Solution

  • Return the promise created by the .then method:

    app.service('MyUser', ['DatabaseRef', 'firebase', function(DatabaseRef, firebase) {
        //var pseudonym ="";
        var userId = firebase.auth().currentUser.uid;
    
        return {
            getUserName: function() {
                //return promise
                return (
                    DatabaseRef.ref('/users/' + userId).once('value')
                        .then(function onSuccess(snapshot) {
                            let pseudonym = snapshot.val().pseudonym;
                            console.log("pseudony: ", pseudonym);
                            return pseudonym;
                    })
                );
            }
        }
    }]);
    

    Then extract the value from that promise:

    var app = angular.module('app', []);
    app.controller('loginController',['$scope', 'MyUser',function($scope, MyUser)
    {
        let promise = MyUser.getUserName();
        //Extract data from promise
        promise.then( function onSuccess(pseudonym) {
            $scope.pseudonym  = pseudonym;
            console.log($scope.pseudonym);
        });
    }]);
    

    The .then method of an object always returns a promise derived from the value (or promise) returned by the handler function furnished as an argument to that .then method.