我正在使用名爲'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">
喜科裏,我想你的建議,這是行不通的。如果您可以看一看,並且提供了其他建議,我已經添加了服務代碼。謝謝你的幫助。 – manntsheth
它返回具有$ promise屬性的'$ resource'對象。我已經更新了包含'$ promise.then'方法的答案。這是未經測試... – Corey
我試着按照你的第二個解決方案。還是行不通。同樣的錯誤。 – manntsheth