【问题标题】:updating the result of a function realtime实时更新函数的结果
【发布时间】:2017-09-19 20:55:26
【问题描述】:

下面是我用来查询我的 firebase 以搜索其 id 与数组中的数字匹配的玩家的代码:

.controller('mySquadCtrl', ['$scope','$location','$firebaseArray','$firebaseAuth','CommonProp', 'DatabaseService',
 function($scope,$location,$firebaseArray,$firebaseAuth,CommonProp, databaseService){


 var uid = CommonProp.userUid();
 $scope.uid = uid;
 $scope.username = CommonProp.getUser();  

 if(!$scope.username){
$location.path('/welcome');
 }

databaseService.users.child(uid).once('value', function(usersSnapshot){
var users = usersSnapshot.val();
var total = users.total;
var team = users.teamname;

$scope.pick = total; 

var orderedPlayers = databaseService.players.orderByChild("id");
$firebaseArray(orderedPlayers)
        .$loaded(function(loadedPlayers) {
        var normalizedPlayers = loadedPlayers.reduce(function(acc, next) { acc[next.id] = next; return acc; }, {});
        var selectedPlayers = $scope.pick.map(function(num){
            return normalizedPlayers[num];
        });
        $scope.players = selectedPlayers;
                    $scope.sum = function(items, prop){
                    return items.reduce( function(a, b){
                    return a + b[prop];
                    }, 0);
                    };
        $scope.totalPoints = $scope.sum($scope.players, 'goals');    
        $scope.teamname = team;

}, function(err) {
    console.log(err);
    $scope.players = [];
});

 });


 $scope.logout = function(){
 CommonProp.logoutUser();  
}; 

}]);

如果用户未登录,页面会将他们重定向到“主页”。

我的问题是$scope.totalPoints 结果不会实时更新,即使当我直接在数据库中更改$scope.players“目标”值时它也会更新。

当我将值更改为数据库中的$scope.players 值时,有没有办法让$scope.totalPoints 实时更新?

【问题讨论】:

    标签: javascript angularjs firebase firebase-realtime-database angularfire


    【解决方案1】:

    $loaded 承诺只被调用一次:当初始数据已从数据库加载时。它不会在更新时调用。

    要自动更新总和,您需要扩展 $firebaseArray。请参阅AngularFire documentation for an example of extending an array to include a total。另一个很好的例子,见the answer to this question

    【讨论】:

    • 我不太明白 $extend 是如何工作的。所有示例都在工厂中使用它。由于我的代码中没有工厂,这是否意味着我必须在 $scope.totalPoints 函数更新之前创建工厂?
    • 是的。这确实是示例所做的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多