这是我的第一个角度项目,我正在构建一个天气应用程序,它从用户在输入字段中输入的特定位置获取天气数据。
我目前遇到的一个问题是,如果您键入一个位置,然后键入另一个位置,延迟的承诺具有与最后一个相同的位置和天气信息(有两个异步调用)。
我为我的这里项目做了一个柱塞。如果你去那里打开你的控制台,输入两个位置,你会注意到对象有相同的信息。
我知道这个柱塞上有很多文件;但是,唯一相关的文件是:MainController.js、getWeatherData.js、setWeatherData.js和getLocationData.js。
下面是getWeatherData工厂的一个片段,它从forecast.io获取天气数据并将其作为承诺返回(getLocationData非常类似):
(function(){
angular.module("factories")
.factory("getWeatherData", ["$http", "$q", function($http, $q){
var deferred = $q.defer();
var factory = {
getData : function(coordinates){
$http.jsonp
(
"https://api.forecast.io/forecast/e1ab2c9f6b96acf85206c6def727a48e/" + coordinates + "?callback=JSON_CALLBACK"
)
.then(
function(response){
deferred.resolve(response);
}
);
},
promise : function(){
return deferred.promise;
}
};
return {
factory : factory
};
}]);
})();发布于 2015-10-12 17:52:35
所以,问题是我是如何制造工厂的。此外,正如@ste2425在上面的评论中指出的那样,$http返回了一个承诺。尽管如此,在使用http请求时,没有理由使用$q .只是个多余的东西。我研究了工厂,发现了这。
做工厂的时候..。
始终返回宿主对象,而不是显示模块模式,因为对象引用绑定和更新的方式
这是我的新getWeatherData工厂,工作!我也用同样的模式更新了所有其他的。
(function(){
angular.module("factories")
.factory("getWeatherData", ["$http", function($http){
var getWeatherData = {};
getWeatherData.getData = function(coordinates){
return $http.jsonp("https://api.forecast.io/forecast/e1ab2c9f6b96acf85206c6def727a48e/" + coordinates + "?callback=JSON_CALLBACK");
};
return getWeatherData;
}]);
})();发布于 2015-10-12 06:56:12
工厂应以这种方式使用:
.factory("getWeatherData", ["$http", "$q", function($http, $q){
var deferred = $q.defer();
return {
getData : function(coordinates) {
$http.jsonp(
"https://api.forecast.io/forecast/e1ab2c9f6b96acf85206c6def727a48e/" + coordinates + "?callback=JSON_CALLBACK"
).then(function (response) {
deferred.resolve(response);
})
return deferred.promise
}
}
}])https://stackoverflow.com/questions/33073381
复制相似问题