I'm building a weather app where I first have to get the users location, then make the request to get the weather.
So I have a GeolocationService
and a WeatherService
. My WeatherService
is currently calling the Geolocation
Service. How do I make the WeatherService
wait until it has the results from the GeolocationService
before making the HTTP request?
app.factory('GeolocationService',function($q,$window,$rootScope){ return { getLatLon: function(){ var deferred = $q.defer(); if(!window.navigator){ $rootScope.$apply(function(){ deferred.reject(new Error("Geolocation not available")); }); } else { $window.navigator.geolocation.getCurrentPosition(function(position){ $rootScope.$apply(function(){ deferred.resolve(position); }); }, function(error){ $rootScope.$apply(function(){ deferred.reject(error); }); }); } return deferred.promise; } }; }); app.factory("WeatherService", function ($q,$http,$rootScope, GeolocationService) { return { getWeather: function(){ var weather; var loc = new GeolocationService.getLatLon(); var lat= loc.lat || 37.4568202221774, lon= loc.lon || -122.201366838789 ; var units = ''; var url = 'http://api.openweathermap.org/data/2.5/forecast/daily?lat='+lat+'&lon='+lon+'&units='+units+'&callback=JSON_CALLBACK'; $http.jsonp(url) .success(function(data) { weather=data; return weather; }) .error(function(err){ weather=err; return err; }); } }; });
$apply
, not sure what the thinking is there – charlietfl