Felice
Felice

Reputation: 581

Adding Firebase Data to Angular Service?

I am trying to inject my Firebase Object to a service so I can use different Angular Controllers to access copies of the Firebase Object.

In a previous working copy of my app. I only loaded Firebase into a controller:

Example Below:

  ToDo.controller('todoController',["$scope","$firebaseArray", function($scope, $firebaseArray, ToDoData){ // injecting AngularFire & ToDoData Service 


  var myData = new Firebase("https:firebase url goes here"); //create Firebase obj
  $scope.todos = $firebaseArray(myData); //Reading Database and adding to todos variable 

  $scope.historytodos = [{'title': "Old Task", 'done':true, 'timetag':new Date().toString()}];

  $scope.addTodo = function(){

    var datecreated = new Date().toString();

    $scope.todos.$add({'title':$scope.newtodo,'done':false, 'timetag': datecreated}); //push to Array 

    $scope.newtodo = '';
  };

Now I am trying to recreate the Firebase Dependency , but to work with a service. Here is what I have for my attempted Service.

It is erroring this Uncaught ReferenceError: Todo is not defined

Example of my Erroneous service :

Todo.value('fbURL', "https:firebase") //Firebase URL value service
.service('fbRef',function(fbURL){ //Firebase Data Reference Service
  return new Firebase(fbURL);
})
.service('fbArr',function(fbRef){ //Firebase Array service
  $scope.todos = $firebaseArray(fbRef);
  return $scope.todos;
});

Not sure what's causing the error & also not too sure how to create a service to hold my Firebase object.

Upvotes: 1

Views: 911

Answers (1)

André Kool
André Kool

Reputation: 4968

First of all the error is self explanatory, Todo is not defined. You have to do something like:

var Todo = {fbRef: "https:firebase"};

And for the service i suggest you read up on services and factory's to see what applies best for your particular case and here is a simple example of how to do it in a service:

.service('fb', function(){
  var connection = new Firebase(url);
  var todos = $firebaseArray(connection);

  this.url = function() { return connection;};
  this.todos = function() { return todos;};
});

Upvotes: 2

Related Questions