Jo Pfeffer
Jo Pfeffer

Reputation: 65

Scope Variable calling http service stays undefined

This might be a beginner question, but why does the $scope.usercountry Variable stays undefinded, although the service is successful?

http://jsfiddle.net/9twyLna1/

var myApp = angular.module('myApp', []);

myApp.factory('myService', function ($http) {
return {

    userCountry: function () {
        $http.get("http://ipinfo.io/json").success(function (data) {
            var userCountry = data.country;
            alert(userCountry);
            return userCountry;
        });

    }

  };

});

function MyCtrl($scope, myService) {
$scope.usercountry = myService.userCountry();
}

Upvotes: 1

Views: 947

Answers (1)

kanhai shah
kanhai shah

Reputation: 1333

$http works in asynch way, what it means is when you call a service userCountry, an asynch call to the end point will be made and code will come back to the calling function. So basically you are trying to show the data before it is actually fetched. This is the basic behaviour when you work with promises.

To overcome this you will need to return a promise from the service and from calling function you should wait until data comes back from http request.

you can read about this here. updated fiddle : http://jsfiddle.net/9twyLna1/3/

var myApp = angular.module('myApp', []);
myApp.factory('myService', function ($http) {
    return {

        userCountry: function () {
            return $http.get("http://ipinfo.io/json");
        }

    };

});

function MyCtrl($scope, myService) {
    $scope.usercountry = myService.userCountry().then(function(data){
      return data.data.country;        
    });
}

Upvotes: 2

Related Questions