Mikail Mikail - 7 months ago 9
Javascript Question

angular js getting out variable from $http is service

Hi I have created a service which gets a json from a remote server, not I need to get the result and set it as a property of the service, but I don't know how to get the property out of the function

app.service('varService',['$http', function($http){
var ip = myip;
window.city = '';
$http.get('http://ip-api.com/json/'+ip)
.then(function(data) { window.city = data.data.city; });

this.city=city;
}]);


the property
this.city
doesn't receive any value , however when I do
console.log
inside
.then()
the value exists, how do I solve the problem, how do I get value out of
$http.then()
?

Answer

There you can't get data return by ajax as soon as you execute that line of code, you should use .then callback to retrieve data over there. You could use .then over $http call to get data from ajax.

app.service('varService',['$http', function($http){
    var ip = myip;
    var self = this;
    self.getCity = function (){
       return $http.get('http://ip-api.com/json/'+ip)
       .then(function(data) { 
           self.city = data.data.city; 
           return self.city; //do return city retrieved  
       });
    }
}]);