I have a problem. I am making an application AngularJS and when inject a factory in a controller gives me undefined. The problem is when I call factory. I am not able to get the value of the response.
Factory:
app.factory('mapFactory', function($http){
return {
getCoordinates: function() {
return $http.get("http://xxxx/map.php?callback=JSON_CALLBACK").then(function(response){
return response.data;
console.log(response.data); // "37.344/-4.3243"
});
}
}
});
Controller:
app.controller('MapCtrl', function(mapFactory) {
var coordinates;
mapFactory.getCoordinates().then(function(response){
return coordinates = response;
});
console.log(coordinates); // undefined
var elem = coordinates.split('/'); // Cannot read property 'split' of undefined
latitude = elem[0];
longitude = elem[1];
});
The $http.get
call is asynchronous, so coordinates = response
will be set when the get requerst finished, but the following code will be executed immediately. You could move the rest of the code into the then
function to make it work
app.controller('MapCtrl', function(mapFactory) {
var coordinates;
mapFactory.getCoordinates().then(function(response){
return coordinates = response;
console.log(coordinates);
var elem = coordinates.split('/');
latitude = elem[0];
longitude = elem[1];
});
});