javascript - AngularJS JSON 对象在 View 中可访问,但在 Controller 中不可访问

标签 javascript json angularjs model-view-controller

我有一个获取一些 openWeather JSON 的简单服务。然后将服务注入(inject) Controller 。在 Controller 中,我无法使用 JSON 访问对象,但是,当绑定(bind)到时,我可以毫无问题地访问对象数据。我是 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"});

}]);

Controller

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

最佳答案

您正在使用 $http promise 。日志语句在数据从服务器返回之前触发。试试这个:

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

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

关于javascript - AngularJS JSON 对象在 View 中可访问,但在 Controller 中不可访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32344522/

相关文章:

javascript - php中remove删除行后如何重新排序序列号

javascript - json 文件未从 Visual Studio 2013 加载

javascript - AngularJS json.parse json数据第1行第1列的数据意外结束

angularjs - 将输入绑定(bind)到 array.length 时出现 RangeError

angularjs - 如何在angularJS中为数字添加千位分隔逗号?

javascript - Cordova 文件传输插件下载总是产生 http 状态 401 和错误代码 3

javascript - 命名点击事件绑定(bind)javascript

java - JSON jsonObject.optString() 返回字符串 "null"

javascript - 在 Meteor 中获取嵌套 JSON 格式的数据

ios - 没有找到与 RestKit 的可映射关系值 keyPath