2016-01-20 96 views
2

我正在使用名爲'forecastController'的Angular.js控制器。無法讀取angular.js控制器中的json響應屬性

Angular.js控制器代碼:

weatherApp.controller('forecastController', 
    ['$scope','$routeParams','cityService', 'weatherService', function($scope, $routeParams , cityService, weatherService) 
{  
    $scope.city=cityService.city; 
    $scope.days=$routeParams.days || '2' ; 
    $scope.weatherResult=weatherService.GetWeather($scope.city, $scope.days); //I get valid json response, the format is mentioned down below. 
    console.log($scope.weatherResult.city.name); //Not working, this is the problem 
}]); 

JSON對象 '$ scope.weatherResult' 是:

{ 
    "city":  
    { 
    "id": 2643743, 
    "name": "London", 
    "coord": { 
     "lon": -0.12574, 
     "lat": 51.50853 
    }, 
    "country": "GB", 
    "population": 0 
    }, 
    "cod": "200" 
} 

我的服務是

weatherApp.service('weatherService', ['$resource',function($resource){ 
    this.GetWeather=function(city, days){ 

     var weatherAPI=$resource("http://api.openweathermap.org/data/2.5/forecast/daily?APPID={{MY_API_KEY_GOES_HERE}}",{ 
     callback:"JSON_CALLBACK"}, {get:{method:"JSONP"}}); 

     return weatherAPI.get({q:city, cnt:days});  
    }; 
}]); 

我 'forecastController' 接收有效的$ scope.weatherResult。在HTML視圖中,我可以訪問weatherResult json對象屬性。我已經確保它正確。例如,{{weatherResult.city.name}}起作用。但是,如果我嘗試在我的'forecaseController'內的console.log中打印,我會得到未定義的值。我得到的JSON數據是從http://openweathermap.org/api

我得到的錯誤是:

TypeError: Cannot read property 'name' of undefined 
    at new <anonymous> (http://127.0.0.1:50926/controllers.js:19:42) 
    at e (https://code.angularjs.org/1.3.0-rc.2/angular.min.js:36:215) 
    at Object.instantiate (https://code.angularjs.org/1.3.0-rc.2/angular.min.js:36:344) 
    at https://code.angularjs.org/1.3.0-rc.2/angular.min.js:72:460 
    at link (https://code.angularjs.org/1.3.0-rc.2/angular-route.min.js:7:268) 
    at Fc (https://code.angularjs.org/1.3.0-rc.2/angular.min.js:68:47) 
    at K (https://code.angularjs.org/1.3.0-rc.2/angular.min.js:57:259) 
    at g (https://code.angularjs.org/1.3.0-rc.2/angular.min.js:49:491) 
    at https://code.angularjs.org/1.3.0-rc.2/angular.min.js:49:99 
    at https://code.angularjs.org/1.3.0-rc.2/angular.min.js:50:474 <div ng-view="" class="ng-scope"> 

回答

0

您的服務weatherService.GetWeather可能會返回一個承諾。在該承諾解決之前,您的$scope.weatherResult對象中的屬性將不確定。使用承諾then方法:

$scope.weatherResult = weatherService.GetWeather($scope.city, $scope.days); 
$scope.weatherResult.$promise.then(function() { 
    console.log($scope.weatherResult.city.name); 
}); 

更新:按照我的意見,服務返回一個$resource對象。該對象有一個$promise屬性。

Link To Codepen

+0

喜科裏,我想你的建議,這是行不通的。如果您可以看一看,並且提供了其他建議,我已經添加了服務代碼。謝謝你的幫助。 – manntsheth

+0

它返回具有$ promise屬性的'$ resource'對象。我已經更新了包含'$ promise.then'方法的答案。這是未經測試... – Corey

+0

我試着按照你的第二個解決方案。還是行不通。同樣的錯誤。 – manntsheth

相關問題