2015-07-10 70 views
2

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

但即时得到错误

类型错误:无法读取属性 '然后'在控制器中未定义

请帮忙

+0

也许是因为[navigator.geolocation.getCurrentPosition](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/ getCurrentPosition)无返回 – Hacketo

+0

CurrentLocation的值为{对象:纬度:11.9384867,经度:79.8352657} –

+0

看起来那段代码'return navigator.geolocation.getCurrentPosition' – Hacketo

回答

3

navigator.geolocation.getCurrentPosition(function() {}) return 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 
    } 
}; 

}); 
+0

Thnku Krzysztof Safjanowski ..它工作正常...但我在控制器中获取的数据说未定义..实际上它需要一些时间来获取位置数据在服务。但在此之前,我的控制器正在执行..你可以告诉如何处理这 –

+0

@KarthikYeruva - 修复,对不起,没有检查它的答案 –

+0

谢谢这么多@Krzysztof Safjanowski ....它正在工作... –

相关问题