Reputation:
.factory('someFac', function (CONFIG, $injector, $http) {
return $http.get('url').then(function (response) {
var temp = response.data.answer;
var answer = '';
if(temp == bar){
answer = barAnswer;
}
else if(temp == foo){
answer = fooAnswer;
}
return $injector.get(answer);
}
}
So my problem is, the $http.get isn't finished getting the response before the factory is finished executing...how should I fix this? I read somewhere I could implement the app.config to inject variables into a provider...could that be a solution?
Upvotes: 1
Views: 574
Reputation: 436
Your factory/service should be what is maintaining the data and the controller should just use it (this way 2-way binding can occur across different controllers).
.factory('someFac', function ($http) {
var self = this;
self.init = function() {
return $http.get('url').then(function(response) {
self.data = response.data;
});
}
}
Now your factory can be injected anywhere and maintains the data, so all of your controllers will be updated real time. To make sure the data is loaded make sure to put the init into a resolve in the route.
resolve: {
someFac: function (someFac) {
return someFac.init();
}
}
Now in a controller you can just use it as so:
.controller('someControleler', function ($scope, someFac) {
$scope.data = someFac.data;
});
Hope this helps.
Upvotes: 1
Reputation: 2799
Usually a factory will just return the promise from calling a method with $http and then the code that called the factory will handle the ".then" when the promise is fulfilled.
.factory('someFac', function (CONFIG, $injector, $http) {
var fact = {}
fact.getResponse = function (){
return $http.get('url');
}
return fact;
}
Upvotes: 0