调用 http 服务的范围变量保持未定义

Scope Variable calling http service stays undefined

这可能是一个初学者问题,但是为什么 $scope.usercountry 变量保持未定义状态,尽管服务已成功?

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();
}

$http以异步方式工作,意思是当你调用服务userCountry时,将对端点进行异步调用,代码将返回到调用函数。所以基本上你试图在实际获取数据之前显示数据。这是使用 promises 时的基本行为。

要克服这个问题,您需要 return 来自服务和调用函数的承诺,您应该等待数据从 http 请求返回。

您可以阅读此内容 here。 更新 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;        
    });
}