Search code examples
javascriptangularjsangularjs-service

How to make angular's services available to independent objects ; Angular JS


In my angular app, I am trying to make a dataAdapter factory where I can quickly switch between the local adapter and the api adapter during development and publishing.

My dataAdapter factory looks like this

myApp.factory('dataAdapter', function($http, $q){
   var dataAdapter = new apiAdapter;
   //var dataAdapter = new localAdapter;
    return dataAdapter;
});

and my adapter objects (here api adapter) would looks something like this. (This will be located in another file called apiAdapter.js )

var apiAdapter = function(){
  return {
    getData : function(){ $http.get(). ....; }
  }
}

Now this isn't working for me, because $http is not available inside apiAdapter object. Now if I move var apiAdapter = function(){....} just before var dataAdapter = new apiAdapter; , it works fine. Is there a way to make the angular services available to apiAdapter without moving it inside the factory?

I hope, I have been able to describe my problem clearly.


Solution

  • I don't really see a point in sharding that small functionality so in my opinion it should look like

    myApp.factory('dataAdapter', function($http, $q){
        return {
          getData : function(){ $http.get(). ....; }
        }
    });
    

    but if you have to do it for some reason

    myApp.factory('dataAdapter', function($http, $q){
       var dataAdapter = new apiAdapter($http);
       //var dataAdapter = new localAdapter;
        return dataAdapter;
    });
    
    var apiAdapter = function(http){//
      return {
        getData : function(){ http.get(). ....; }
      }
    }