Mikail Mikail - 2 years ago 129
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 = '';
.then(function(data) { window.city = data.data.city; });


the property
doesn't receive any value , however when I do
the value exists, how do I solve the problem, how do I get value out of

Answer Source

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  
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download