AngularJS JSON对象在视图中可访问,但在控制器中无法访问

时间:2015-09-02 04:11:11

标签: javascript json angularjs model-view-controller

我有一个简单的服务,可以获得一些openWeather JSON。然后将服务注入控制器。在控制器中,我无法使用JSON访问对象,但是,当绑定到时,我可以毫无问题地访问对象数据。我是JS和Angular的新手,我做错了什么?

服务

mcmdApp.service('areaWeatherService', ['$resource', function($resource){

    this.weatherAPI = $resource("http://api.openweathermap.org/data/2.5/weather", {get: {method: "JSON"}});
    this.weatherResult = this.weatherAPI.get({q: "London,uk"});

}]);

控制器

mcmdApp.controller('SingleElementController',['$scope', 'areaWeatherService',function($scope, areaWeatherService){

    $scope.weatherResult = areaWeatherService.weatherResult;
    console.log($scope.weatherResult); //<-- Shows Object in Console
    console.log($scope.weatherResult.wind); //<-- PROBLEM: Shows Undefined
    console.log($scope.weatherResult.wind.speed); //<-- PROBLEM: Shows cannot read property 'speed' of Undefined

}]);

查看

<div class="single-element-widget text-center">
    <h2>{{weatherResult.wind.speed}} mph</h2><!-- NO PROBLEM, displays correctly -->
    <small>{{weatherResult.wind.deg}} degrees</small><!-- NO PROBLEM, displays correctly -->
</div>

我试图从Controller或服务中访问对象和属性。

console.log($scope.weatherResult);

的结果
e {$promise: d, $resolved: false}$promise: d$resolved: truebase: "cmc stations"clouds: Objectcod: 200coord: Objectdt: 1441164423id: 2643743main: Objectname: "London"sys: Objectweather: Array[1]wind: Object__proto__: e

1 个答案:

答案 0 :(得分:4)

您正在使用$http承诺。在从服务器返回数据之前,将触发log语句。试试这个:

$scope.weatherResult = areaWeatherService.weatherResult.$promise.then(function(resp){
 console.log(resp);
 console.log(areaWeatherService.weatherResult.wind);
});

.then()将等待您的承诺得到解决,然后执行生成的代码