无法访问返回的对象 - 资源服务

时间:2016-07-23 03:02:02

标签: angularjs

这是我的第一个Angular应用程序,所以我确定有一些显而易见的错误,但我已经用Google搜索并搜索了这个网站而没有任何运气。

我使用$ resource服务进行AJAX调用以从weather API获取一些JSON。下面的函数检索它(通过weatherService的功能),我能够成功地将返回的对象记录到屏幕(console screenshot)。当我尝试访问任何对象的属性(例如info.cnt)时,记录它将返回 undefined 。无法弄清楚为什么会这样。任何帮助将非常感激。

$scope.submit = function() {
    var info = weatherService.getForecast(weatherService.city);
    console.log(info);
}

我的定制气象服务:

weather.service('weatherService', function($resource){

    this.city = 'Chicago, IL';

    this.getForecast = function(location) {

        this.weatherAPI = $resource("http://api.openweathermap.org/data/2.5/forecast/daily", { callback: "JSON_CALLBACK" }, { get: { method: "JSONP" }});

        this.weatherResult = this.weatherAPI.get({ q: this.city, cnt: 5, appid: 'e92f550a676a12835520519a5a2aef4b' });

        return this.weatherResult;
    }

});

3 个答案:

答案 0 :(得分:0)

您的来电将被执行异步。所以,您的服务应该是:

weather.service('weatherService', function($resource){

    this.city = 'Chicago, IL';

    this.getForecast = function(location) {

        this.weatherAPI = $resource("http://api.openweathermap.org/data/2.5/forecast/daily", { callback: "JSON_CALLBACK" }, { get: { method: "JSONP" }});

        return this.weatherAPI.get({ q: this.city, cnt: 5, appid: 'e92f550a676a12835520519a5a2aef4b' });

    }

});

你应该消费:

$scope.submit = function() {
    weatherService.getForecast(weatherService.city, function(response) { 
        //DO SOMETHING WITH THE RETURN 
    });
};

您可以看到我们正在传递一个回调,它将在HTTP请求完成时被调用。

如果你想要更进步,你可以而且应该使用承诺。它会变成:

$scope.submit = function() {
   weatherService.getForecast(weatherService.city).$promise.then(function(response){
        //SUCCESS
    }).catch(function(error){
        //ERROR
    });
};

看一下docs,看一些更棒的功能。

所以,为什么你仍然在屏幕上看到相同的数据:

问题是$ resource服务模仿同步操作。给定angular的数据绑定,如果你将你的返回绑定到$ scope,最终将完成响应,并且在$ digest循环期间,框架将重新访问你的变量并看到它有一些数据。但是,正如我所说,这是由于数据绑定,你不能如你所见,立即访问你的数据。

答案 1 :(得分:0)

$ resource service正在返回一个你需要解决的承诺

weatherService.getForecast(weatherService.city).then (function(data){;
        console.log(data);
});

答案 2 :(得分:0)

你只需要这样的解析功能;

$scope.submit = function() {
   weatherService.getForecast(weatherService.city).then(function(res){
     // success handler
      console.log(res);
   },function(error) {
     // error handler
   });
}
相关问题