【问题标题】:TypeError: Cannot read property 'success' of undefinedTypeError:无法读取未定义的属性“成功”
【发布时间】:2014-12-09 23:07:00
【问题描述】:

我正在创建一个用于返回位置坐标的服务。但是我需要一些方法来返回一个值。

angular.module('google.maps', [])
.factory('geocode', ['$http', 'GOOGLE_MAPS_CREDENTIALS', function ($http,GOOGLE_MAPS_CREDENTIALS) {
    return {
        getCoords: function(addr1, zip) {
            $http.get('https://maps.googleapis.com/maps/api/geocode/json?address='
                +encodeURIComponent(addr1+','+zip)+'&sensor=false'
                +'&key='+GOOGLE_MAPS_CREDENTIALS.API_KEY);
        }
    }
}])
.value('GOOGLE_MAPS_CREDENTIALS', { API_KEY: '_____________' });

在这之后,我有一个控制器调用这个函数:

.controller('AddrNewCtrl', ['$scope','$state','$stateParams','geocode','$rootScope','Address',
    function($scope, $state, $stateParams, geocode, $rootScope, Address) {
    $scope.address = {
        userId: {"__type":"Pointer","className":"_User","objectId":$rootScope.user.id}
    };
    $scope.create = function() {
        geocode.getCoords($scope.address.address1, $scope.address.zipCode)
        .success(function(data) { // <-- this is where the console error is.
            var lat = data.results[0].geometry.location.lat;
            var lng = data.results[0].geometry.location.lng;
            $scope.address.location = new Parse.GeoPoint({latitude:lat,longitude:lng});
        });
        Address.create($scope.address)
        .success(function(data) { $state.go('tabs.address-list'); });
    };
}])

问题是当我调用成功时,我得到一个TypeError:

TypeError: Cannot read property 'success' of undefined

我实现此服务的方式与任何其他服务之间几乎没有区别,当我 console.log 数据导致我的 $http.get() 函数时,当我在控制器中调用该函数时,我得到了我期望的所有值.

我正在寻找两个答案之一:

  1. 为什么success 回调会返回错误?
  2. 当我调用geocode 服务时,如何简单地返回一个坐标对象?

【问题讨论】:

  • 错误的主题不是“成功”回调本身。该错误意味着getCoords() 调用没有返回任何内容。
  • 你没有在 getCoords 上返回一个承诺,你应该有 return $http.get
  • 哇,谢谢。这解决了它@Pointy,请随时将其放在答案中,我会给你信任。

标签: javascript angularjs google-maps parse-platform


【解决方案1】:

你应该有

 getCoords: function(addr1, zip) {
         return $http.get('https://maps.googleapis.com/maps/api/geocode/json?address='
            +encodeURIComponent(addr1+','+zip)+'&sensor=false'
            +'&key='+GOOGLE_MAPS_CREDENTIALS.API_KEY);
    }

【讨论】:

    猜你喜欢
    • 2015-10-21
    • 2018-06-02
    • 1970-01-01
    • 1970-01-01
    • 2019-06-21
    • 2021-03-30
    • 2020-08-24
    • 2021-12-10
    • 2020-11-29
    相关资源
    最近更新 更多