angularjs firebase user auth service not communicating with the views

我的梦境 提交于 2019-12-08 04:32:25

问题


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();
}]);

回答1:


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.



来源:https://stackoverflow.com/questions/40058330/angularjs-firebase-user-auth-service-not-communicating-with-the-views

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!