Reputation: 1918
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
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
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();
});
}
}
}
Upvotes: 1