我创建了一个工厂方法,它在从 Controller 中检索值时总是返回 undefined。当我写日志时,它的值完美出现但返回未定义。
.factory('GetLatLongFromAddress', ['$http', '$q', function ($http, $q) {
var LatnLong =
{
Latitude: 0.00,
Longitude: 0.00
}
return {
GetLatLong: function (address) {
var geocoder = new google.maps.Geocoder();
var address = address;
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK)
{
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
LatnLong.Latitude = latitude;
LatnLong.Longitude = longitude;
console.log(LatnLong);
}
});
setTimeout(function () { }, 3000);
return LatnLong
},
}
}])
我调用的 myController 是;
$scope.returnValue=(JSON.stringify(GetLatLongFromAddress.GetLatLong("Address")));
那么,你能帮我做这件事吗?
谢谢。
最佳答案
您正在处理对 Google API 的异步请求。因此不会立即收到来自 API 的响应。在您的示例中,您向 API 发送请求并在收到响应之前返回 LatnLong。您已尝试使用 setTimeout 等待响应,但 setTimeout 函数无法正常工作。您的代码示例带有注释:
var geocoder = new google.maps.Geocoder();
var address = address;
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK)
{
// This code will be executed when we receive response from Google API.
// It can be in 2, 3 or 6 seconds.
// We can't tell for sure how much time it will take.
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
LatnLong.Latitude = latitude;
LatnLong.Longitude = longitude;
console.log(LatnLong);
}
});
setTimeout(function () {
// This code will be executed in 3 seconds.
}, 3000);
return LatnLong // This code will be executed immediately. So LatnLong is undefined.
处理异步请求时,您需要使用 promises
您可以通过下一个链接找到更多信息:https://docs.angularjs.org/api/ng/service/ $q
在你的情况下,下一个代码应该可以工作:
var deferred = $q.defer();
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK)
{
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
var LatnLong = {
Latitude: latitude,
Longitude: longitude
};
deferred.resolve(LatnLong);
}
});
return deferred.promise;
此代码将返回 promise,然后您可以通过这种方式将数据放入 $scope:
GetLatLongFromAddress.GetLatLong("Address").then(function(LatLong){
$scope.returnValue= JSON.stringify(LatLong);
});
关于angularjs - 工厂方法总是在 AngularJs 中返回 undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38521809/