AngularJS的JSON对象可以在视图中访问,但不能在控制器中访问

AngularJS JSON object accessible in view, but not accessible in controller

本文关键字:访问 但不能 控制器 JSON 视图 AngularJS 对象      更新时间:2023-09-26

我有一个简单的服务,它获得一些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
}]);
<<p> 视图/strong>
<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>

我试图从控制器或服务访问对象和属性。

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承诺。日志语句在从服务器返回数据之前触发。试试这个:

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

.then()将等待您的承诺被解决,然后执行结果代码