无法读取angular.js控制器中的json响应属性

时间:2016-01-20 22:07:45

标签: javascript angularjs json callback controller

我正在使用名为' forecastController'。

的Angular.js控制器

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});     
    };
}]);

我的预测控制器'收到有效的$ 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">

1 个答案:

答案 0 :(得分:1)

您的服务weatherService.GetWeather可能会返回承诺。在解除该承诺之前,$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