AngularJS 使用 $resource 从 API 获取 json 数据,获取未定义

AngularJS using $resource to get json data from API, getting undefined

我从 ipCity 和 ipCountry 得到未定义,未定义

但我不明白为什么。

weatherApp.service('cityService', function ($resource) {

    var ipLocation = $resource("http://ipinfo.io", {callback: "JSON_CALLBACK"}, {get: {method: "JSONP"}});
    var ipResult = ipLocation.get();
    var ipCity = ipResult.city;
    var ipCountry = ipResult.country;

    console.log(ipResult);

    this.city = ipCity + ", " + ipCountry;
})

日志:

d {$promise: d, $resolved: false}
$promise: d
$resolved: true
city: "Toronto"
country: "CA"
hostname: "CPE00fc8d503cf3-CM00fc8d503cf0.cpe.net.cable.rogers.com"
ip: "99.232.37.198"
loc: "43.6555,-79.3626"
org: "AS812 Rogers Cable Communications Inc."
postal: "M5A"
region: "Ontario"
__proto__: d

所以我基本上是从 API 获取数据,但我不能将这些数据用于我的服务。

您需要提供回调函数。另外,请注意数据不会立即在您的服务中。

var self = this;
    ipResult.$promise.then(function(data)
    {
       var ipCity = data.city;
       var ipCountry = data.country;

        console.log(data);

        self.city = ipCity + ", " + ipCountry;  
    });