【问题标题】:service is returning undefined in the array in angularjs服务在angularjs的数组中返回未定义
【发布时间】:2015-12-23 15:16:39
【问题描述】:

我的 angularjs 脚本遇到了问题。

背景:我正在尝试确定用户的位置,我已经在我的服务中编写了我的业务逻辑,我从中返回用户的位置。

问题:我在控制台中得到的结果如下:

[未定义]landingPage.js:11 未定义landingPage.js:11 未定义

var app = angular.module("PublicEvents", ["geolocation"]);

app.controller("iterator", ["$scope", "$http", "locationService1", function($scope, $http, locationService1){
    $scope.targetCity = [];
    $scope.targetCity.push(locationService1.location());

    console.log($scope.targetCity);
    $scope.$watch(function () { return locationService1.cityNameArray; },
            function (value) {
        $scope.targetCity = value;
        console.log($scope.targerCity);
    }
    );

}]);



app.service("locationService1",['$http','$window', function( $http, $window){
    var access = this;
    this.location = function(){
        $window.navigator.geolocation.getCurrentPosition(function(position) {
            access.lat = position.coords.latitude;
            access.long = position.coords.longitude;

            access.locationData = [];
            access.cityNameArray = [];

            /*var url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=18.9750,72.8258&sensor=true";*/
            var url = "http://maps.googleapis.com/maps/api/geocode/json?latlng="+access.lat+","+access.long+"&sensor=true";

            //AJAX CALL TO GET THE LOCATION
            $http.get(url).then(function(response) {
                access.locationData = response.data; 
                if(access.locationData.status == "OK" || access.locationData.status==200 ) {
                    angular.forEach(access.locationData.results, function(value, key){
                        var len = value.address_components.length;
                        for(var i = 0; i< len; i++){
                            if(value.address_components[i].types[0] =="locality" || value.address_components[i].types[0] =="sublocality_level_1"){
                                access.cityNameArray.push(value.address_components[i].long_name);
                            }
                        }
                    }); 
                };
            }); 
            return access.cityNameArray;
        });
    };
}]);

【问题讨论】:

  • landingPage.js 中的第 11 行是什么?
  • console.log($scope.targetCity); $watch 里面
  • 我认为这可能是这个问题的重复:stackoverflow.com/questions/25575963/…
  • angular 将在您创建它时触发观察器一次,因为服务器没有返回任何内容但您的值未定义。 Pankaj 的回答似乎也不错。 :)
  • 让我看看你给的链接....

标签: javascript angularjs angularjs-service angular-promise angularjs-factory


【解决方案1】:

似乎您需要从异步调用中返回数据,并且您正在从函数外部返回值。我建议你在这种情况下使用 Promise 模式。

this.location = function(){
    $window.navigator.geolocation.getCurrentPosition(function(position) {
        access.lat = position.coords.latitude;
        access.long = position.coords.longitude;

        access.locationData = [];
        access.cityNameArray = [];

        /*var url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=18.9750,72.8258&sensor=true";*/
        var url = "http://maps.googleapis.com/maps/api/geocode/json?latlng="+access.lat+","+access.long+"&sensor=true";

        //return promise from here..
        return $http.get(url).then(function(response) {
            access.locationData = response.data; 
            if(access.locationData.status == "OK" || access.locationData.status==200 ) {
                angular.forEach(access.locationData.results, function(value, key){
                    var len = value.address_components.length;
                    for(var i = 0; i< len; i++){
                        if(value.address_components[i].types[0] =="locality" || value.address_components[i].types[0] =="sublocality_level_1"){
                            access.cityNameArray.push(value.address_components[i].long_name);
                        }
                    }
                }); 
            };
            return access.cityNameArray; //returned from success callback
        }); 

    });
};

在控制器内部,您需要使用.then 函数从服务loacation 函数中获取数据。当您执行不返回任何内容的异步调用时,您正在执行 console.log

locationService1.location().then(function(data){ //success callback.
   $scope.targetCity.push(data)
},function(error){ //error callback.
   console.log(error)
});

【讨论】:

  • 我没有看到定位函数返回任何承诺。
  • @toskv 感谢您的提醒.. 我正在编辑我的答案.. TYSM
  • 是否需要返回 access.cityNameArray 和 promise...实际上我收到错误无法读取未定义的属性 'then'
  • @PragamShrivastava 是的,您需要同时返回 return $http.get(url).access.cityNameArray
  • 我分离了导航器功能后它工作了!谢谢:)
猜你喜欢
  • 2017-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多