2016-01-25 32 views
0

谁能告诉我,为什么我得到以下几点:

在我的控制,我使用角资源指令做一个正常调用的API。

$scope.weatherAPI = $resource('http://api.openweathermap.org/data/2.5/forecast/daily', {callback: 'JSON_CALLBACK'}, {get: {method: 'JSONP'}}); 
$scope.weatherResult = $scope.weatherAPI.get({ q: $scope.city, cnt: 4, APPID: 'xxxxxx' }); 

并将结果打印到控制台。

console.log($scope.weatherResult); 
console.log($scope.weatherResult.city) 

console.log("scope weatherResult " + $scope.weatherResult); 
console.log("scope weatherResult.list: " + $scope.weatherResult.list); 
console.log("scope weatherResult.city: " + $scope.weatherResult.city); 

但是,这是结果。正如你所看到的那样,即使对象是通过$scope.weatherResult进入,当我尝试并定位其中一个属性时,我得到undefined,因此我无法使用该数据。

the results from the console

+0

返回结果是承诺对象,您不应该尝试从属性中检索数据。只需检查文档中的示例https://docs.angularjs.org/api/ngResource/service/$resource – sdfacre

回答

1

从文档:

意识到调用$resource对象方法立即返回一个空引用(对象或数组取决于isArray)是很重要的。一旦数据从服务器返回的现有基准与实际数据填充

- AngularJS $resource API Reference

使用$resource对象的$promise属性的.then方法以提供功能的$q服务,将等待数据解决。

$scope.weatherAPI = $resource('http://api.openweathermap.org/data/2.5/forecast/daily', {callback: 'JSON_CALLBACK'}, {get: {method: 'JSONP'}}); 
$scope.weatherResult = $scope.weatherAPI.get({ q: $scope.city, cnt: 4, APPID: 'xxxxxx' }); 

$scope.weatherResult.$promise.then (function onFulfilled(data) { 
    console.log(data);   
    console.log(data.city); 

    console.log("scope weatherResult " + $scope.weatherResult); 
    console.log("scope weatherResult.list: " + $scope.weatherResult.list); 
    console.log("scope weatherResult.city: " + $scope.weatherResult.city); 
}); 
+0

是的。这就是我忘记的。谢谢。 – PanicBus

相关问题