控制台在块外返回空值但在其中给出正确的值

时间:2018-02-25 17:24:17

标签: javascript angularjs firebase firebase-realtime-database

第二个 if(!textDescriptionLenghtToggle) { // simple boolean toggle ObjectAnimator animation = ObjectAnimator.ofInt( textViewContainingDescription, "maxLines", 6); animation.setDuration(300); animation.start(); } else { ObjectAnimator animation = ObjectAnimator.ofInt( textViewContainingDescription, "maxLines", 2); animation.setDuration(300); animation.start(); } 返回正确的值,但第一个不是。为什么会这样?有人可以帮助我吗?

console.log()

1 个答案:

答案 0 :(得分:0)

在大多数情况下,您的代码将按以下顺序执行

exec 1--> $scope.data = "";

exec 2--> var dataRef = firebase.database().ref("0/"+code);

exec 3--> dataRef.on('value', function(snapshot) { //register event and wait for response asyncronousnly
exec 5-->     console.log(snapshot.val());
exec 6-->     $scope.data = snapshot.val();
});
exec 4--> console.log($scope.data) //at this moment value of $scope.data = ""

所以你可以做的是将代码移到你想要在获取数据后执行的函数(let processData)中,然后像这样调用它

angular.module('resultsApp', ['ngCookies'])

.config(['$qProvider', function ($qProvider) {
    $qProvider.errorOnUnhandledRejections(false);
}])

.controller('resultsController', function($scope) {
    var code = localStorage.getItem('code');
    $scope.data = "";

        var dataRef = firebase.database().ref("0/"+code);

        dataRef.on('value', function(snapshot){
            console.log(snapshot.val());
            $scope.data = snapshot.val();
            console.log($scope.data)
            processData($scope); //call that function here
        });

});