这是我的第一个Angular应用程序,因此我敢肯定我做错了什么,但是我已经在Google上搜索并搜索了该网站,但没有任何运气。
我正在使用$ resource服务进行AJAX调用,以从天气API中获取一些JSON。下面的函数(通过weatherService的函数)对其进行检索,并且我能够成功地将返回的对象记录到屏幕上(控制台屏幕截图)。当我尝试访问该对象的任何属性(例如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;
}
});
您的get调用将异步执行。因此,您的服务应类似于:
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周期内,框架将重新访问变量并查看它是否包含一些数据。但是,就像我说的那样,这是由于数据绑定所致,您不能像您看到的那样立即访问您的数据。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句