0

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.

1
  • 3
    pass $http as paramter to constructor Commented Jul 8, 2014 at 8:49

2 Answers 2

3

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(). ....; }
  }
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.