aayush shrestha
aayush shrestha

Reputation: 1918

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.

Upvotes: 0

Views: 369

Answers (2)

maurycy
maurycy

Reputation: 8465

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(). ....; }
  }
}

Upvotes: 3

Mosho
Mosho

Reputation: 7078

Regardless of your reasons for doing this, this is how it's typically done, in the barest manner:

var $injector = angular.injector(['ng']);

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

docs reference 1

docs reference 2

Upvotes: 1

Related Questions