Search code examples
angularjsangularjs-service

How do you inject dependencies into services in angular.js?


I'm using AngularFire to create a web app. Several of my controllers use a lot of the same functions to access the data in Firebase, so I am trying to write a service so that I don't have to rewrite the same functions for every controller. The problem is that I can't seem to get the Firebase dependency into the service. I'm using the following code:

angular.module("myApp", ["firebase","ngDraggable"])

.factory("GetData",['$firebase','FirebaseConn',function($firebase,FirebaseConn){
    $firebase(new Firebase("https://XXXX.firebaseio.com/")).$asObject().$bindTo(scope, "firebaseData");
    return {

    };
}]);

But when I try to run this, I get the following error:

Unknown provider: FirebaseConnProvider <- FirebaseConn

I am able to access Firebase through my controllers, so it's not a problem connecting to firebase.js or angularfire.js.

How should I inject Firebase into my service so I can access the data in all of my controllers? Or, is there a better way to go about this? I'm rather new to Angular so if there's a better way to share functions between my controllers I'm all ears.


Solution

  • You inject them precisely the same way that you do in Controllers and Directives.

    This is a common error in AngularJS, and it means you're injecting something that isn't injectable. It almost always means either you missed a dependency (probably not in this case) or that you're asking for something that doesn't exist in the first place.

    This is almost certainly your problem. You're asking for firebase and getting it, but it can't find FirebaseConn. What is that, some variable of yours that you're using to track your connection? Because you aren't using it, and the AngularFire docs I just looked at don't, either.

    Consider something more like the following:

    angular
        .module("myApp", ["firebase", "ngDraggable"])
        .service("firebaseManager",['$firebase', function($firebase) {
            var ref = new Firebase("https://XXXX.firebaseio.com/"),
                sync = $firebase(ref);
    
            this.getData = function() {
                return sync.$asObject();
            };
        });
    

    Obviously, customize this to suit. Two comments:

    1. You probably do want a service instead of a factory. This is a common point of confusion when you first start using AngularJS. You only need a factory if you plan to get involved in the instantiation of the service in some way. A service is just a shortcut form of a factory with the most common usage - the one you probably want.

    2. You will now inject this service firebaseManager into your controllers. When you do, they will be able to call firebaseManager.getData() and any other methods you define. firebaseManager will be a singleton, so all of this will go through one common Firebase connection.