Firebase AngularFire in AngularJS Service

The best way to handle Firebase in AngularJS should certainly be from within the service, so it is available to all controllers through the application.

I just can't get it to work! ... I first tried using angularFire(new Firebase(url)) , hoping I could snap to the service area, but Angular complains that it can't $watch it.

So, I tried angularFireCollection as follows:

 app.factory('myService', function myService(angularFireCollection) { var url = 'https://myfirebase.firebaseio.com'; return { getAll: function(path) { var ref = angularFireCollection(new Firebase(url + '/' + path)); console.log(ref); return ref; }, ... }; }); 

However, angularFireCollection is an object containing a load of methods, etc., if I bind it to the space of the $ controller, I just get garbage. He also complains that he cannot call Firebase functions before I try to use them (for example, Error: Firebase.push failed: second argument must be a valid function. ) ... who has ideas that I am mistaken in?

See PLUNKER

+8
angularjs angularjs-service firebase angularfire
source share
2 answers

If you want to encapsulate some functions in a service, consider keeping the returned ref in service state. I have expanded your plunker. It seems that basically do what you tried to do.

http://plnkr.co/edit/Uf2fB0

+12
source share

Jeff answered the question correctly ... I just post further development on the example of Jeff for those who are interested.

I have distracted the creation of the Firebase service so that you can dynamically create an instance of any Firebase service you want: -

 var registerFirebaseService = function (serviceName) { app.factory(serviceName, function (angularFire) { var _url = null; var _ref = null; return { init: function (url) { _url = url; _ref = new Firebase(_url); }, setToScope: function (scope, localScopeVarName) { angularFire(_ref, scope, localScopeVarName); } }; }); }; 

First create an instance of the service as follows

 registerFirebaseService('itemsService'); // create itemsService instance 

You can then enter the itemsService into your controllers. An instance is initialized using a Firebase URL, for example.

 itemsService.init('https://firebase.firebaseio.com/' + userId + '/items'); 

Now Firebase can be tied to your controller, for example.

 itemsService.setToScope($scope, 'items'); 

adapted by PLUNKER

+6
source share

All Articles