【问题标题】:AngluarJS and Firebase, Updating table using servicesAngluarJS 和 Firebase,使用服务更新表
【发布时间】:2016-09-15 02:36:32
【问题描述】:

我有一个表,我想用从我的 firebase 数据库中获取的数据进行更新。我知道 firebase 调用返回一个承诺,然后数据库调用异步运行,但即使在 .then 方法中,我似乎也无法将异步数据提取到我的表视图中。

为了克服异步部分,我尝试使用服务(基于此答案Update scope value when service data is changed)。我使用了测试回调方法addValue()来测试添加数据。但是,当我在 firebase 的 .then() 查询中使用此回调时,服务的数据已更新,但视图中并未更新。

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

             });
            }
        });
    }
  })();

});

【问题讨论】:

  • 建议研究使用angularFire。所有使用 firebase 的事件都需要直接告诉 Angular 运行摘要,因为数据是在 Angular 上下文之外检索的。 angularfire 让 3 路绑定变得非常简单
  • 谢谢,我会调查的!

标签: javascript angularjs web firebase-realtime-database


【解决方案1】:

当使用 firebase 时,这经常发生在 Angular 中。在您的addValue() 方法中,尝试在您的推送逻辑之后添加$scope.apply()

例子:

this.addValue=function(){
    var self=this;
    self.data.push({name : "Sam" , score : 180});
    $scope.apply();
}

$scope.apply() 用于更新视图以反映控制器中所做的事情。

希望对你有帮助

【讨论】:

  • 服务中没有$scope
  • 我可以使用 $rootscope 吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-15
  • 2015-10-29
  • 1970-01-01
  • 2018-08-27
  • 2019-10-19
  • 2017-06-16
相关资源
最近更新 更多