且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

angularjs firebase 用户身份验证服务未与视图通信

更新时间:2023-12-03 15:30:04

返回.then方法创建的promise:

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

对象的 .then 方法总是返回一个从处理函数返回的值(或承诺)派生的承诺,作为该 .then 方法的参数提供.

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.