2015-07-10 93 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 ....它正在工作... –

相關問題