Angular JS承诺和ng重复

Angular JS promises and ng-repeat

本文关键字:ng 重复 承诺 JS Angular      更新时间:2023-09-26

我有两个问题。我所做的是要求提供邮政编码,使用API获取该邮政编码的纬度和经度,然后使用该纬度和经度使用英国警方API获取该地点附近特定日期的所有街头犯罪。问题是ng repeat不起作用,我想这是因为当页面加载时,$http请求仍然没有收到任何回复,因为如果我控制台日志,它会返回未定义的结果,然后使用setTimeout两秒钟后,它就会返回我需要的内容。

这是我的代码:

function PostCodeCtrl($scope, Server, $location, $routeParams){
this.postcode = $routeParams.postcode;
if(this.postcode){
    this.title = "dasdasd";
    this.crimes = undefined;
    Server.get("http://api.postcodes.io/postcodes/" + this.postcode)
        .then(function(response){
        this.response = response.data;
        if(response.data.status === 200){
            Server.get('http://data.police.uk/api/crimes-street/all-crime?lat='+ 
                        this.response.result.latitude +
                        '&lng='+
                        this.response.result.longitude+
                        '&date=2013-01').then(function(response){
                this.crimes = response.data;
            });
        }
    });
    console.log(this.crimes); //returns undefined
    setTimeout(function(){
        console.log(this.crimes); //returns JSON object
    }, 2000);
}else{
    $location.path('/');
}

}

<ul>
    <li ng-repeat="crime in postcode.crimes">
        {{crime.category}}
    </li>
</ul>

我也不明白承诺的意义,在看了至少5个youtube上的视频和演示后,他们都说承诺有助于摆脱金字塔代码,也就是这样的东西:

(function($) {
  $(function(){
    $("button").click(function(e) {
      $.get("/test.json", function(data, textStatus, jqXHR) {
        $(".list").each(function() {
          $(this).click(function(e) {
            setTimeout(function() {
              alert("Hello World!");
            }, 1000);
          });
        });
      });
    });
  });
})(jQuery);

但我不认为它有助于你仍然必须像我的第一个例子那样把东西嵌套在里面,它仍然创建了金字塔结构。

这里有两个问题,让我们来分解一下。

如何在ng-repeat中加载异步数据

给定以下内容:

<div ng-repeat="item in items">
  {{item.title}}
</div>

如果$scope.items是异步设置的,那么ng-repeat在将$scope.items设置为某个数组之前不会渲染任何内容,然后Angular将检测到更改并更新View:

$http.get("data.json").then(function(response){
   $scope.items = response.data; // data is the array of items
});
console.log($scope.items); // undefined, since $http has not yet received the reponse

如何在没有"回调地狱"的情况下链接承诺

promise是可链式的,其中每个.then处理程序将数据或数据的另一个promise返回给行中的下一个人:

$http.get("/someService")
  .then(function(response){
     var data = response.data;
     return // important!
       $http.get("/someOtherService", { d: data });
  })
  .then(function(response){
    var data2 = response.data;
    // do something
    return finalData;
  };

你可以看到它是如何连锁的。如果你把所有这些都放在你的服务中:

.factory("Svc", function($http){
    getFinalData: function(){
       return $http.get("/someService")
         // etc.. (as above)
    }
})

然后在控制器中,您可以执行以下操作:

.controller("MainCtrl", function(Svc){
   Svc.getFinalData().then(function(data){
     $scope.items = data; // could be used with ng-repeat
   });
});