Angular JS - 将 Firebase 数据从服务传递到控制器

Angular JS - Passing Firebase data from Service to Controller

我正在尝试将我的 Firebase 数据从服务传递到控制器,但出现错误:TypeError: MeetingNamesService.myCalTimes is not a function.

服务:

angular.module('app.services', [])

.factory('MeetingNamesService', [function($firebaseArray){

    var myCalTimes = new Firebase("https://xxxxxxxx.firebaseio.com");

    myCalTimes.on("value", function(snapshot) {
        var calTimes = snapshot.val();
        return $firebaseArray(calTimes);        

    }, function (errorObject) {
      console.log("Data failed: " + errorObject.code);
    });
}])

控制器:

.controller('monthsCtrl', function($scope, MeetingNamesService, $ionicLoading) {

    $scope.times = MeetingNamesService.myCalTimes();
    $scope.times = calTimes;    
    console.log($scope.times);
})

知道为什么它不能将 myCalTimes 识别为函数吗?谢谢

试试这个

angular.module('app.services', [])

.factory('MeetingNamesService', ['$firebaseArray', function($firebaseArray){
    // this instead of var
    this.myCalTimes = new Firebase("https://xxxxxxxx.firebaseio.com");

    this.myCalTimes.on("value", function(snapshot) {
        var calTimes = snapshot.val();
        return $firebaseArray(calTimes);        

    }, function (errorObject) {
      console.log("Data failed: " + errorObject.code);
    });
}])

让工厂中的函数像这样将回调作为参数:

function foo(callback) {
            fbRef.on('value', function (dataSnapshot) {
                        callback(dataSnapshot.val());
                    });
        }

并像这样使用它:

service.foo(setFoo);
setFoo = function(data) {
// Use data here
}

.on() 函数 returns 一个承诺而不是一个函数 :)

获取数据后需要return服务:

angular.module('app.services', ['firebase'])

.factory('MeetingNamesService', ['$firebaseArray', function($firebaseArray){
  var myCalTimes = new Firebase("https://xxxxxxxx.firebaseio.com");
  return {
    getCalTimes: getCalTimes
  }
  function getCalTimes() {
      return $firebaseArray(mycalTimes);        
  }
}]);

你的控制器应该像下面这样调用函数:

.controller('monthsCtrl', function($scope, MeetingNamesService, $ionicLoading) {
  $scope.times = MeetingNamesService.getCalTimes();
  console.log($scope.times);
});