Factory Method始终在AngularJs中返回undefined

时间:2016-07-22 08:35:07

标签: angularjs

我创建了一个工厂方法,它总是在从控制器检索值时返回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")));        

那么,你能帮助我吗?

谢谢。

2 个答案:

答案 0 :(得分:3)

您正在使用针对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);
});

答案 1 :(得分:1)

你没试过超时吗? BTW为什么在这里空超时?