简体   繁体   English

在迭代angularjs期间处理rest API

[英]Handle rest API during iteration angularjs

How to handle this code snippet from the given fiddler. 如何处理来自给定提琴手的代码片段。

for (var i = 0; i < carList.length; i++) {
    $http.get("accesoriesList.htm").then(function(accesories) {
      $scope.accesoriesList.push({"id": carId, "name": carName, "accesories" : accesories});
}

Fiddler https://jsfiddle.net/gsk/euuhsowu/ 提琴手 https://jsfiddle.net/gsk/euuhsowu/

I am trying to get list of accessories of a car. 我正在尝试获取汽车配件清单。 But I got different issue: 但是我有不同的问题:

  1. Rest call were fired asynchronous and didn't set accessories to their respective car item 休息呼叫被异步触发,并且未为其各自的汽车物品设置配件
  2. I would expect to set accessories based on car item since rest API has fired in iteration but I get only one response that set to all accessories. 我希望可以根据汽车项目设置配件,因为rest API已在迭代中触发,但是我只收到一个设置为所有配件的响应。
  3. Rest API were fired in iteration so I expect to get carList.length response instead I get one response. Rest API在迭代中被触发,因此我希望得到carList.length响应,而不是一个响应。

You should think async always. 您应该始终认为异步。 Sequential async calls should be putted within previous callback's functions. 顺序异步调用应放在先前的回调函数中。

So the second API calls ( accesoriesList.htm ) should be inside the first callback: 因此,第二个API调用( accesoriesList.htm )应该位于第一个回调中:

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

    $http.get("carList.htm").then(function(data) {
      for (var i = 0; i < data.length; i++) {
            $scope.carList.push({"id": data[i].carId, "name": data[i].carName});
      }

      for (var i = 0; i < $scope.carList.length; i++) {
        $http.get("accesoriesList.htm").then(function(accesories) {
          $scope.accesoriesList.push({"id": carId, "name": carName, "accesories" : accesories});
        });
      }

  });

});

Maybe it's just an example, but I think that the second call should have some routing rule to receive the carId... 也许这只是一个例子,但我认为第二个呼叫应该有一些路由规则来接收carId ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM