首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用来自另一个工厂中的一个工厂的异步数据

使用来自另一个工厂中的一个工厂的异步数据
EN

Stack Overflow用户
提问于 2016-06-14 22:25:57
回答 2查看 163关注 0票数 0

我正在尝试使用来自angular的一家工厂的地理位置数据,在另一家工厂查询天气API以获取数据。我不知道如何在两个工厂之间共享lat/lng变量,我知道你已经使用了$scope,但是我不能得到angular-promise来正确工作。目前有静态的lat/lng变量。控制器中的定位函数甚至不能打印到控制台,我想我的promise函数有问题。

以下是工厂:

代码语言:javascript
复制
'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);
            });
        }
    };
}]);

这是控制器

代码语言:javascript
复制
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
    }
});

我是Angular的新手,非常感谢来自社区的任何帮助,我想在这里更积极!提前谢谢。

诚挚的问候,

-MC

EN

回答 2

Stack Overflow用户

发布于 2016-06-14 22:31:52

首先,不要在出厂时使用$SCOPE ,$scope只在控制器上可用。

你的问题的解决方案很简单。让weatherFactory通过返回lat/long来公开它们:

代码语言:javascript
复制
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);
            });
        }
    };

然后,将weatherFactory注入到geolocationService中,您将能够访问lat/lon:

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2016-06-29 23:21:56

这样如何:

代码语言:javascript
复制
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);
        }
    };
}]);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37814832

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档