【问题标题】:AngularJS JSON object accessible in view, but not accessible in controllerAngularJS JSON对象在视图中可访问,但在控制器中不可访问
【发布时间】:2015-11-27 10:51:10
【问题描述】:

我有一个简单的服务,可以获取一些 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>

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

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

【问题讨论】:

  • 发布console.log($scope.weatherResult)的结果;
  • 编辑:我已经添加了console.log($scope.weatherResult);的结果

标签: javascript json angularjs model-view-controller


【解决方案1】:

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

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

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

【讨论】:

  • 返回错误“.then 不是函数”。但是,在.then() 之前添加$promise 之后,像这样$scope.weatherResult = areaWeatherService.weatherResult.$promise.then(function(resp){ console.log(resp); 它似乎正在工作。这是正确的代码吗?
  • 哎呀!是的,这是正确的。我会为其他人相应地更新我的答案。恭喜你解决了!
  • 如果我将$promise.then 移动到服务,以便在传递到控制器之前在服务中发送和接收数据,那么我将如何访问resp 对象与控制器?场景:假设我想将检索到的数据注入到多个控制器中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-22
  • 1970-01-01
  • 1970-01-01
  • 2018-04-24
  • 2019-04-03
  • 1970-01-01
相关资源
最近更新 更多