我試圖在查詢天氣API數據的另一家工廠使用角度中的一家工廠的地理位置數據。我無法弄清楚如何在兩個工廠之間共享lat/lng變量,我知道你已經使用了$ scope,但是我無法獲得正確的角度承諾。目前有靜態的經緯度變量。控制器中的定位功能甚至不能打印到控制檯,我認爲我的承諾功能有問題。在另一家工廠使用來自一家工廠的異步數據
這裏是工廠:
'use strict';
app.config(['$resourceProvider', function ($resourceProvider) {
$resourceProvider.defaults.stripTrailingSlashes = false;
}]);
app.factory("geolocationService", ['$q', '$window', '$rootScope', function ($q, $window, $rootScope) {
return {
currentLocation: function() {var deferred = $q.defer();
if (!$window.navigator) {
$rootScope.$apply(function() {
deferred.reject(new Error("Geolocation is not supported"));
});
} else {
$window.navigator.geolocation.getCurrentPosition(function (position) {
$rootScope.$apply(function() {
deferred.resolve(position);
var geoJ = $scope.data;
//console.log(position);
});
}, function (error) {
$rootScope.$apply(function() {
deferred.reject(error);
});
});
}
return deferred.promise;
}
}
}]);
app.factory('weatherFactory', ['$http','geolocationService', function ($http, $scope, geolocationService) {
//var currentLocation = geolocationService.currentLocation();
var apiKey = 'd079ba76e47f06f2ea3483892f1b1d40';
var lat = '40',
lon = '-79';
return {
currentForecast: function(callback){
var url = ['https://api.forecast.io/forecast/', apiKey, '/', lat, ',', lon, '?callback=JSON_CALLBACK'].join('');
$http.jsonp(url)
.success(function (data){
callback(null, data);
//console.log("weatherFactory API Call: ");
//console.log(data);
})
.error(function (error) {
callback(error);
});
}
};
}]);
,這裏是控制器
app.controller('weatherCtrl', function ($scope, $window, weatherFactory, geolocationService) {
//console.log(geolocationService.currentLocation());
//var location = geolocationService.currentLocation();
//console.log("location object: ");
//console.log(location);
var locate = function(){
geolocationService.currentLocation().then(function(location){
$scope.location = location;
console.log($scope.location);
});
};
var pollForecast = function pollForecast() {
var commutes = calculateNextCommutes();
weatherFactory.currentForecast(function (err, data) {
if (err) {
$scope.forecastError = err;
} else {
$scope.forecast = data;
$scope.nextCommute = findCommuteWeather(commutes.nextCommute, $scope.forecast.hourly.data);
$scope.nextNextCommute = findCommuteWeather(commutes.nextNextCommute, $scope.forecast.hourly.data);
}
});
};
$scope.init = function() {
pollForecast();
setInterval(function() {
console.log('polling weather every hour')
pollForecast();
}, 1000 * 60 * 60); //poll every hour
}
});
我很新的角度和希望得到來自社會的幫助,我想成爲在這裏更活躍!提前致謝。
最好的問候,
-MC
謝謝你的快速回應! 有一個問題,它仍然顯示LAT處於不確定的: 回報{ 緯度:緯度, LON:LON, – khalamoska
它仍然試圖調用API天氣運行geolocationService,發現$ window.navigator.getolocation前,因此經緯度未定義。在weatherFactory調用weather API之前,我如何才能使weatherCtrl等到它被發現? – khalamoska
您需要使用承諾'.then()' – Tomer