gpt4 book ai didi

javascript - 无法读取 angular.js Controller 中的 json 响应属性

转载 作者:行者123 更新时间:2023-11-29 15:31:00 24 4
gpt4 key购买 nike

我正在使用名为“forecastController”的 Angular.js Controller 。

Angular.js Controller 代码是:

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 View 中,我可以访问 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">

最佳答案

您的服务 weatherService.GetWeather 可能会返回一个 promise 。在该 promise 得到解决之前,您的 $scope.weatherResult 对象中的属性将是未定义的。使用 promise 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

关于javascript - 无法读取 angular.js Controller 中的 json 响应属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34911575/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com