我有一个表,想要使用从 Firebase 数据库获取的数据进行更新。我知道 firebase 调用返回一个 promise ,然后数据库调用运行异步,但即使在 .then 方法中,我似乎也无法将异步数据提取到我的 TableView 中。
为了克服异步部分,我尝试使用服务(基于这个答案 Update scope value when service data is changed )。我使用测试回调方法addValue()
来测试添加数据。但是,当我在 firebase 查询的 .then() 内部使用此回调时,服务的数据已更新,但在 View 中未更新。
routerApp.controller('leaderboardCtrl', function($scope, service) {
$scope.data = service.data;
service.getLeaderboard('Test1', 'TestGroup', 10);
//service.getValues();
}).factory("service", function($rootScope, $q)
{
return new (function AsyncTest(){
this.data=[
{name : "Sam" , score : 190}
]
this.getValues=function()
{
var self=this;
//self.data.push({name : "Sam" , score : 180});
self.addValue();
self.count++
},
this.count=0,
this.addValue =function(){
var self=this;
self.data.push({name : "Sam" , score : 180});
}
this.getLeaderboard = function(test, groupName, limit){
var self=this;
var uid = currentUser.uid;
firebase.database().ref('/groupMembers/' + groupName).once('value').then(function(snapshot) {
for(var user in snapshot.val()){
firebase.database().ref('/tests/' +test + '/users/' + user).orderByChild("score").limitToLast(limit).once('value').then(function (snapshot) {
console.log('----LEADERBOARD----');
console.log(snapshot.val());
self.addValue();
console.log(self.data);
});
}
});
}
})();
});
最佳答案
在 Angular 中使用 firebase 时,这种情况经常发生。在您的 addValue()
方法中,尝试在推送逻辑之后添加 $scope.apply()
。
示例:
this.addValue=function(){
var self=this;
self.data.push({name : "Sam" , score : 180});
$scope.apply();
}
$scope.apply()
用于更新 View 以反射(reflect) Controller 中所做的操作。
希望这有帮助
关于javascript - AngluarJS 和 Firebase,使用服务更新表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39497256/