我正在构建一个天气应用程序,我首先必须获取用户的位置,然后发出获取天气的请求。
所以我有一个GeolocationService和一个WeatherService。我WeatherService目前正在致电Geolocation服务。如何在发出 HTTP 请求之前WeatherService等待它得到结果?GeolocationService
app.factory('GeolocationService',function($q,$window,$rootScope){
返回 {
getLatLon:函数(){
var deferred = $q.defer();
如果(!window.navigator){
$rootScope.$apply(function(){
deferred.reject(new Error("地理位置不可用"));
});
} 别的 {
$window.navigator.geolocation.getCurrentPosition(函数(位置){
$rootScope.$apply(function(){
deferred.resolve(位置);
});
},函数(错误){
$rootScope.$apply(function(){
deferred.reject(错误);
});
});
}
返回 deferred.promise;
}
};
});
app.factory("WeatherService", function ($q,$http,$rootScope, GeolocationService) {
返回 {
获取天气:函数(){
var 天气;
var loc = new GeolocationService.getLatLon();
var lat= loc.lat || 37.4568202221774,
lon= loc.lon || -122.201366838789;
变量单位 = '';
var url = 'http://api.openweathermap.org/data/2.5/forecast/daily?lat='+lat+'&lon='+lon+'&units='+units+'&callback=JSON_CALLBACK';
$http.jsonp(网址)
.成功(功能(数据){
天气=数据;
返回天气;
})
.错误(函数(错误){
天气=错误;
返回错误;
});
}
};
});