GreenDome
GreenDome

Reputation: 277

Angular JS - Passing Firebase data from Service to Controller

I am trying to pass my Firebase data from a Service to Controller but getting an error: TypeError: MeetingNamesService.myCalTimes is not a function.

Service:

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:

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

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

Any idea why it's not recognising myCalTimes as a function? Thanks.

Upvotes: 2

Views: 1435

Answers (3)

Shaohao
Shaohao

Reputation: 3511

You need to return the service after you fetch the data:

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

You controller should call the function like following:

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

Upvotes: 1

Let the function in the factory take a callback as argument like this:

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

And use it like this:

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

the .on() function returns a promise and not a function :)

Upvotes: 0

AlainIb
AlainIb

Reputation: 4708

try this

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

Upvotes: 0

Related Questions