2016-01-25 31 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

相關問題