我在 Angular.js 工厂中有一个对象:
angular.module('myapp')
.factory('geoLocationService', function () {
var geoLocationObj = {};
var geocoder = new google.maps.Geocoder();
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(_successFunction, _errorFunction);
}
function _successFunction(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({'latLng': latlng}, function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
if (results[2]) {
geoLocationObj.resultCity = results[2].formatted_address;
alert(geoLocationObj.resultCity);
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
return geoLocationObj;
});
这有效 alert(geoLocationObj.resultCity);
并在属性值中发出警报
但是
console.log(geoLocationObj);
不记录属性geoLocationObj.resultCity
我试图在 Controller 的工厂外部使用geoLocationObj.resultCity
,但它不在那里。
我的 Controller 中有:
.controller('IndexCtrl', function ($scope, geoLocationService) {
var geoLocationService = geoLocationService;
console.log(geoLocationService);
geoLocationService
是一个空对象
我不明白为什么会发生这种情况。 你能帮我解决这个问题吗?
最佳答案
代码中的问题是您的对象在回调 (_successFunction) 中初始化,这意味着返回的对象仍然为空,因为 _successFunction 尚未被调用。
您应该使用 $q 返回一个 Promise 并在 Controller 中调用 .then()。
angular.module('myapp')
.factory('geoLocationService', ['$q', function ($q) {
var geoLocationObj = {};
var deferred = $q.defer();
var geocoder = new google.maps.Geocoder();
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(_successFunction, _errorFunction);
}
function _successFunction(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({'latLng': latlng}, function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
if (results[2]) {
deferred.resolve(results[2].formatted_address);
alert(geoLocationObj.resultCity);
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
return deferred.promise;
})];
在你的 Controller 中
.controller('IndexCtrl', function ($scope, geoLocationService) {
geoLocationService.then(function(geoLocObj){
console.log(geoLocObj); Here your object has been resolved
});
关于javascript - 对象属性不是在工厂成员函数内创建的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28674549/