函数内的 HTTP 请求不起作用

HTTP Request inside a function not works

我有这个用于 AngularJS 框架的控制器。

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {


 var locations =[]; var map; var markers = [];

$scope.mappa = function(){
    map = new google.maps.Map(document.getElementById('map'), {
        center: {lat: 37.507033, lng: 15.080257}, 
        zoom: 8
      });
}

$scope.insert = function(){

         $http.get("http://localhost:8080/SistemiDistribuiti/rest/Point/Trovati")
    .success(function(data) 
            {locations = data;});

    var marker, i;

    for (i = 0; i < locations.length; i++) {  
        marker = new google.maps.Marker({
             position: new google.maps.LatLng(locations[i][0], locations[i][1]),
             map: map
        });
        markers.push(marker);
    }

    for (i = 0; i<markers.length; i++){
     markers[i].setVisible(true);
   }
};

在 html 文件中,我有一个调用插入函数的按钮。 但是如果我 运行 这段代码,按钮只在第二次工作。相反,如果 http 请求超出该功能,则该按钮会立即起作用。为什么?

$http.get("http://localhost:8080/SistemiDistribuiti/rest/Point/Trovati")
.success(function(data) 
        {locations = data;});

$scope.insert = function(){

var marker, i;

for (i = 0; i < locations.length; i++) {  
    marker = new google.maps.Marker({
         position: new google.maps.LatLng(locations[i][0], locations[i][1]),
         map: map
    });
    markers.push(marker);
}

for (i = 0; i<markers.length; i++){
 markers[i].setVisible(true); }
};

But if I run this code, the button works at the second time only.

它第一次工作,只是 AJAX 请求是异步的,所以当您尝试使用它时 location 变量还没有填充。下次点击的时候,发现已经加载了数据,设置了location和"cached".

你需要在回调函数中做你的事情:

$scope.insert = function () {

    $http.get("http://localhost:8080/SistemiDistribuiti/rest/Point/Trovati").success(function (data) {
        var marker, i, locations = data;

        for (i = 0; i < locations.length; i++) {
            marker = new google.maps.Marker({
                position: new google.maps.LatLng(locations[i][0], locations[i][1]),
                map: map
            });
            markers.push(marker);
        }

        for (i = 0; i < markers.length; i++) {
            markers[i].setVisible(true);
        }       
    });

};

最后,当你让它工作时,考虑将你的请求逻辑移动到可重用服务中,在控制器中发出请求不是最好的设计:

$scope.insert = function () {
    locations.get().then(function(data) {
        var marker, i, locations = data;
        // ...
    });
};

这是异步方法。将代码插入回调成功。

$http.get("http://localhost:8080/SistemiDistribuiti/rest/Point/Trovati")
.success(function(data) {
    var marker, i;

    for (i = 0; i < data.length; i++) {  

        marker = new google.maps.Marker({
             position: new google.maps.LatLng(data[i][0], data[i][1]),
             map: map
        });

        markers.push(marker);
    }

    for (i = 0; i<markers.length; i++){
        markers[i].setVisible(true); }
    }
});