TypeError:无法读取属性'然后'未定义的

时间:2015-07-10 09:34:42

标签: angularjs

我的Service.js

appnService.factory('LocationService', function(){

var currentLocation = {
    latitude:"",
    longitude:""
}

 return {
   GetLocation : function(){
     return navigator.geolocation.getCurrentPosition(function(pos){
            currentLocation.latitude = pos.coords.latitude;
            currentLocation.longitude= pos.coords.longitude;
          return currentLocation;
     });
   }
 };

});

我的控制器

appne.controller('NewObservationCtrl',function($scope,$state,LocationService) {     
LocationService.GetLocation().then(function(data){
console.log(data);
});
});

但我得到了错误

TypeError:无法读取属性'然后'在控制器中未定义

请帮忙

1 个答案:

答案 0 :(得分:3)

navigator.geolocation.getCurrentPosition(function() {})返回undefined。如果您需要承诺,则必须使用位置值

来解析延迟对象
.factory('LocationService', function ($q) {

var currentLocation = {
    latitude: "",
    longitude: ""
}

return {
    GetLocation: function () {
        var d = $q.defer();
        navigator.geolocation.getCurrentPosition(function (pos) {
            currentLocation.latitude = pos.coords.latitude;
            currentLocation.longitude = pos.coords.longitude;
            d.resolve(currentLocation);
        });
        return d.promise
    }
};

});