工厂方法在AngularJs中始终返回未定义
我创建了一个工厂方法,当从控制器检索值时,它总是返回未定义的。当我写日志时,它的值是完美的,但返回的是未定义的工厂方法在AngularJs中始终返回未定义,angularjs,Angularjs,我创建了一个工厂方法,当从控制器检索值时,它总是返回未定义的。当我写日志时,它的值是完美的,但返回的是未定义的 .factory('GetLatLongFromAddress', ['$http', '$q', function ($http, $q) { var LatnLong = { Latitude: 0.00, Longitude: 0.00 } return { GetLa
.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
},
}
}])
我所召唤的我的控制者是
$scope.returnValue=(JSON.stringify(GetLatLongFromAddress.GetLatLong("Address")));
那么,你能在这方面帮助我吗
多谢各位 您尝试过没有$timeout吗?顺便问一下,为什么这里有空超时?您正在处理对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.
处理异步请求时,需要使用承诺
您可以通过下一个链接找到更多信息:$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);
});
你注射了吗?你能帮我提供更多细节吗?因为我是安格拉新手。我也试过了,没有超时。我想我只需要睡眠2秒钟,其中返回变量get-datainject意味着将'GetLatLongFromAddress'添加到控制器:Ctrl.$inject=['GetLatLongFromAddress'];函数Ctrl(GetLatLongFromAddress){}谢谢。我在控制器定义中添加了。即控制器('addcompanyController'、['$scope'、'$http'、'$theme'、'$location'、'$rootScope'、'$routeParams'、'GetLatLongFromAddress',函数($scope、$http、$theme、$location、$rootScope、$routeParams、GetLatLongFromAddress){且不带JSON.stringify?不带JSON.stringify为我提供了带有0的默认值对象。即{纬度:0.00,经度:0.00}