my Service.js
我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;
});
}
};
});
my controller
我的控制器
appne.controller('NewObservationCtrl',function($scope,$state,LocationService) {
LocationService.GetLocation().then(function(data){
console.log(data);
});
});
But im getting the error
但是我得到了错误
TypeError: Cannot read property 'then' of undefined in controller
TypeError:无法读取控制器中未定义的属性。
Please help
请帮助
1 个解决方案
#1
3
navigator.geolocation.getCurrentPosition(function() {})
return undefined
. If you want promise you must resolve deferred object with position value
navigator.geolocation.getCurrentPosition(函数(){ })返回定义。如果你想要承诺,你必须用位置值来解析递延对象
.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
}
};
});
#1
3
navigator.geolocation.getCurrentPosition(function() {})
return undefined
. If you want promise you must resolve deferred object with position value
navigator.geolocation.getCurrentPosition(函数(){ })返回定义。如果你想要承诺,你必须用位置值来解析递延对象
.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
}
};
});