AngularJS工厂返回数据未定义

时间:2014-08-14 23:23:52

标签: angularjs factory

我试图将一个geoDataFactory注入venueDataFactory。当currentPosition被记录到控制台时,结果是未定义的,而假设成功获取坐标,currentPosition应该是包含地理位置数据(包括纬度和经度)的对象。为什么不明确?

angular.module('myApp', ['ionic','ngCordova'])
    .factory('geoDataFactory', function($cordovaGeolocation, $location) {
       var currentPosition = {
           'latitude': 0,
           'longitude': 0,
           'altitude': 0,
           'accuracy': 0,
           'altitudeAccuracy': 0,
           'heading': 0,
           'speed': 0,
           'timestamp': 0
       };

       var getCurrentPosition = function() {
           $cordovaGeolocation.getCurrentPosition().then(function(position) {
               // Position here: position.coords.latitude, position.coords.longitude
               currentPosition.latitude = position.coords.latitude;
               currentPosition.longitude = position.coords.longitude;
               currentPosition.altitude = position.coords.altitude;
               currentPosition.accuracy = position.coords.accuracy;
               currentPosition.altitudeAccuracy = position.coords.altitudeAccuracy;
               currentPosition.heading = position.coords.heading;
               currentPosition.speed = position.coords.speed;
               currentPosition.timestamp = position.coords.timestamp;
               return currentPosition;
           }, 
           function(err) {
               // error
               console.log("Error with cordova geolocation.currentPosition");
               return err;
           });
       };

       return {
           position: getCurrentPosition()
       }
    })
    .factory('venueDataFactory', function($q, $timeout, geoDataFactory) {
        var currentPosition = geoDataFactory.position;
        console.log(currentPosition);
    })

1 个答案:

答案 0 :(得分:1)

我认为在position返回任何数据之前会返回getCurrentPosition。正如安东尼所说,你应该回复getCurrentPosition的承诺。您可以在return前面添加$cordovaGeolocation.getCurrentPosition().then...来实现。这样,position: getCurrentPosition()就会返回承诺。

然后在你的venueDataFactory中,你调用该函数,当promise被解决后,它将返回位置,你可以将它分配给你的变量。它看起来像这样:

.factory('venueDataFactory', function($q, $timeout, geoDataFactory) {
    geoDataFactory.position().then(function (response) {
        var currentPosition = response;
        console.log(currentPosition);
    });
})