[英]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: 但是我有不同的问题:
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.