2016-06-14 2 views
0

날씨 API에서 데이터를 쿼리하는 다른 팩토리의 각도에서 한 공장의 Geolocation 데이터를 사용하려고합니다. 두 공장간에 lat/lng 변수를 공유하는 방법을 알아낼 수는 없지만 $ 범위를 사용한다는 것을 알고 있지만 제대로 작동한다는 확신을 얻을 수는 없습니다. 현재 정적 lat/lng 변수가 있습니다. 컨트롤러의 locate 함수는 콘솔에 출력하지 않습니다. 내 약속 함수에 문제가 있다고 생각합니다. 여기 다른 공장의 한 공장에서 비동기 데이터 사용

는 공장이다 : 나는 각도에 매우 새로 온 사람과 지역 사회에서 어떤 도움을 주셔서 감사합니다 것 컨트롤러

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 
    } 
}); 

여기

'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); 
      }); 
     } 
    }; 
}]); 

그리고, 나는 싶습니다 여기에서 더 적극적으로! 미리 감사드립니다.

최고 감사합니다, 모두의

- MC

답변

0

첫째, 공장 IN DONT 사용 $의 범위는 $ 범위는 컨트롤러에서만 사용할 수 있습니다.

문제는 매우 간단합니다. weatherFactory가 노출이있는 위도/경도 그들을 반환하여 :

return { 
     lat: lat, 
     lon: lon, 
     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); 
      }); 
     } 
    }; 

을 그리고, geolocationServiceweatherFactory를 주입하고 액세스 할 수 있습니다 위도/경도 :

app.factory("geolocationService", ['$q', '$window', '$rootScope', 'weatherFactory', function ($q, $window, $rootScope , weatherFactory) { 
    return { 
     currentLocation: function() {var deferred = $q.defer(); 
      var lat = weatherFactory.lat; 
      var lon = weatherFactory.lon; 
      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; 
     } 
    } 
}]); 
+0

빠른 답장을 보내 주셔서 감사합니다. 는 문제가 여전히 위도을 보여주는 것은에서가 정의되지된다 반환 { 위도 : 위도, 경도 : 경도, – khalamoska

+0

여전히 GeoLocationService에 실행 및 $ window.navigator.getolocation을 발견하기 전에 날씨 API를 호출하려고 따라서 위도/경도는 정의되지 않습니다. weatherCtrl을 weatherFactory를 사용하여 weather API를 호출하기 전에 찾을 때까지 weatherCtrl을 대기 시키려면 어떻게합니까? – khalamoska

+0

'.then() '과 함께 약속을 사용해야합니다. – Tomer

0

이 방법에 대해 :

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); 
        }); 
       }, function (error) { 
        $rootScope.$apply(function() { 
         deferred.reject(error); 
        }); 
       }); 
      } 
      return deferred.promise; 
     } 
    } 
}]); 

app.service('weatherService', ['$http','geolocationService', function ($http, $scope, geolocationService) { 
    var apiKey = '...'; 
    return function(callback){ 
      //Note - a better, more angularish way to do this is to return the promise 
      //itself so you'll have more flexability in the controllers. 
      //You also don't need callback param because angular's $http.jsonp handles 
      //that for you 
      geolocationService.currentLocation().then(function(location){ 
      var url = ['https://api.forecast.io/forecast/', apiKey, '/', location.lat, ',', location.lon, '?callback=JSON_CALLBACK'].join(''); 
      return $http.jsonp(url) 
      .then(function(data){ callback(null,data); }) 
      catch(callback); 
     } 
    }; 
}]);