【问题标题】:How to call one HTTP Call inside another HTTP Call in a for loop in AngularJS?如何在AngularJS的for循环中调用另一个HTTP调用中的一个HTTP调用?
【发布时间】:2020-05-06 08:23:28
【问题描述】:

我正在开发一个 AngularJS 应用程序。 我有以下数组:

$scope.fruits = [
 {url1: 'appleColor', url2: 'appleDetail'},
 {url1: 'orangeColor', url2: 'orangeDetail'},
 {url1: 'grapesColor', url2: 'grapesDetail'},                 
];

现在,我正在调用这样的 HTTP GET 请求:

for(var i = 0; i < $scope.fruits.length; i++){
   var fruit = $scope.fruits[i];
   getFruitColor(fruit.url1).then(function(color){
      getFruitDetail(fruit.url2).then(function(detail){
         console.log("color is "+ color);
         console.log("detail is "+ detail);
      }):
   });
}

function getFruitColor(url){
   return $http({
        method: 'GET', url: url, params: {} }).then(getFruitComplete, getFruitFailed);
}

function getFruitDetail(url){
    return $http({ method: 'GET', url: url, params: {} }).then(getFruitDataComplete, getFruitDataFailed);
}

function getFruitDataComplete(response) {
    return response.data;
}
        
function getFruitDataFailed(error) {
    $log.error('Failed to get fruit data - '  + error.data);
}
        
function getFruitComplete(response) {
    return response.data;
}
        
function getFruitFailed(error) {
    $log.error('Failed to get fruit- '  + error.data);
}

现在,由于所有这些调用都是异步的,我希望这些调用在 NETWORK 选项卡中像这样(由于异步性质,这些调用的顺序可能不同):

getFruitColor('appleColor')

getFruitColor('orangeColor')

getFruitColor('grapesColor')

getFruitDetail('appleDetail')

getFruitDetail('orangeDetail')

getFruitDetail('grapesDetail')

但我在 NETWORK 选项卡中实际看到的是:

getFruitColor('appleColor')

getFruitColor('orangeColor')

getFruitColor('grapesColor')

getFruitDetail('grapesDetail')

getFruitDetail('grapesDetail')

getFruitDetail('grapesDetail')

我是 AngularJS 和 Javascript 的初学者,我不明白这里有什么问题以及为什么在内部 HTTP 调用中,对于循环中的每个元素,水果数组的最后一个元素的 url2 都会发生。 谁能解释为什么这里会发生这种行为? 我应该怎么做才能达到预期的效果?

【问题讨论】:

  • 你的 for 循环在你的第二个 $http 调用之前就已经结束了。

标签: javascript angularjs loops asynchronous asynchronous-javascript


【解决方案1】:

尝试使用let(或const)而不是var 进行此分配:var fruit = $scope.fruits[i];。类似的东西应该可以解决问题:

for(var i = 0; i < $scope.fruits.length; i++) {
   const fruit = $scope.fruits[i];
   getFruitColor(fruit.url1).then(function(color) {
      getFruitDetail(fruit.url2).then(function(detail) {

还可以考虑使用let i 进行迭代(for(let i = ...)

请注意,var 将被提升到外部范围,并且每次迭代都会覆盖相同的变量。所有对getFruitDetail 的调用将仅使用fruit 的最新值,这就是为什么您会看到3 个使用grapesDetail 的调用。

varlet/const 之间的主要区别在于var 是函数作用域,而let/const 是块作用域。这个链接可能很有趣:https://dev.to/sarah_chima/var-let-and-const--whats-the-difference-69e(或谷歌搜索 var/let/const 之间的区别)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-26
    • 1970-01-01
    相关资源
    最近更新 更多